Java Program to Find Common Elements Between Two Arrays

There are multiple way to Find Common Elements Between Two Arrays.

Using for loop :-

  • First get two string java arrays.
  • Create HashSet object with string type.
  • Now iterate each of every elements one by one.
  • Inside if condition we compare first array element with second array element, if it is equal then add each common element in the HashSet for unique entry data.
  • After print the elements.                                    

Using hashset and retailAll method :-

  • First we convert array element to list from Array.asList() method.
  • Now create two HashSet object and add the list element.
  • Use Collection.retainAll() method to find common elements.this method take only commons element of both the Hashset h1,h2 and keep in h1 HashSet.
  • Now prints the common elements.
				
					import java.util.Arrays;
import java.util.HashSet;

public class CommonELement {
	public static void main(String[] args) {

		String[] s1 = { "one", "two", "three", "five", "eight", "two" };
		String[] s2 = { "nine", "one", "eight", "ten", "five", "one" };
		HashSet<String> hs = new HashSet<String>();
		
		// from for loop
		for (int i = 0; i < s1.length; i++) {
			for (int j = 0; j < s2.length; j++) {
				if (s1[i].equals(s2[j])) {
					hs.add(s1[i]);
				}
			}
		}
		System.out.println("from for loop common elements are :- " + hs);
		
		// from hashset and retailAll method
		HashSet<String> h1 = new HashSet<String>(Arrays.asList(s1));
		HashSet<String> h2 = new HashSet<String>(Arrays.asList(s2));
		h1.retainAll(h2);
		System.out.println("from hashset and retailAll method common elements are :-" + h1);
	}
}

				
			

Output :-
from for loop common elements are :- [one, five, eight]
from hashset and retailAll method common elements are :- [one, five, eight]