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.
Output:

Common Elements Between Two Arrays: 4 5

Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Regular Expression part 2 in java
Find out words occurrences in a file
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

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 […]

Leave a Reply

Your email address will not be published. Required fields are marked *