# Find common elements among two unsorted arrays

Sometimes, you may face this situation that you have 2 arrays and both are unsorted. You need to compare them and find out the common values. How to find out common elements in 2 unsorted arrays?

Suppose, you are extracting data from Database as well as from front end Application. Now, you need to compare the data extracted from both the sources.Let’s see with an example.

In the example below, we have 2 Integer arrays which are having some values. There are following steps which you will perform to complete the job.

### Steps:

• Compare the length of both the array and find the small one.
• Iterate through small array and put unique values in a HashSet.
• Iterate through large array and find the elements stored in the previous Hashset.
• If find common value, add to a new array.
• Display final array.
```package com.array;

import java.util.HashSet;

public class CommonValUnsortedArray {

public static void main(String[] args) {

Integer[ ] arrayFirst = { 4,3,7,2,4,0,8,2,5};
Integer[ ] arraySecond = { 9,5,9,4,1};

Integer[ ] commonValues = CommonValUnsortedArray.findCommonValues( arrayFirst, arraySecond );

System.out.print( "Common Elements Between Two Arrays: " );
for( Integer vaule : commonValues ) {
System.out.print( vaule + " " );   //Display the common values
}

}

public static Integer[ ] findCommonValues( Integer[ ] arrayFirst, Integer[ ] arraySecond ) {

Integer[ ] arrStoreCommon;
Integer[ ] arrayToSearch;

if( arrayFirst.length < arraySecond.length ) {
arrStoreCommon = arrayFirst;
arrayToSearch = arraySecond;
} else {
arrStoreCommon = arraySecond;
arrayToSearch = arrayFirst;
}

HashSet<Integer> newArray = new HashSet<Integer>( );
HashSet<Integer> hashedArray = new HashSet<Integer>( );

//It will add only unique values into the HashSet
for( Integer value : arrStoreCommon ) {
}

//Check into another array , if value matches then add those values into a new HashSet
for( Integer value : arrayToSearch ) {
if( hashedArray.contains(value) ) {
}
}

return newArray.toArray( new Integer[ 0 ] );
}

}
```

Output:

Common Elements Between Two Arrays: 4 5

Have any question or suggestion for us?Please feel free to post in Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

### 1 Response

1. August 31, 2015

[…] the previous post, we have seen how to find common elements among 2 unsorted arrays. In this post, we will see how to get the count of same word occurrences in a […]