Learnitweb

Write a java program to find common elements between two arrays?

Method 1: Iterative method

In this method, we iterate both the given arrays and compare each element of one array with elements of other array. If the two compared elements are found equal then they add element to a HashSet. The method works well even for arrays which contain duplicate elements.

import java.util.HashSet;

public class CommonElementsBtwnArrayExmpl {
	public static void main(String[] args) {
		String[] arr1 = {"SUN","MON","TUE","WED","THU","FRI","SAT","SUN"};

		String[] arr2 = {"SAT","THU","MON","SUN","SAT"};

		HashSet<String> result = new HashSet<String>();

		for (int i = 0; i < arr1.length; i++) {
			for (int j = 0; j < arr2.length; j++) {
				if (arr1[i].equals(arr2[j])) {
					result.add(arr1[i]);
				}
			}
		}

		System.out.println(result); 
	}
}

Output

[THU, SAT, SUN, MON]

Method 2: Using retainAll() method

HashSet provides retainAll() method. Following is the signature:

public boolean retainAll(Collection<?> c)

This method retains only the elements in this set that are contained in the specified collection (optional operation)

import java.util.Arrays;
import java.util.HashSet;

public class CommonElementsBtwnArrayExmpl {
	public static void main(String[] args) {
		String[] arr1 = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };

		String[] arr2 = { "SAT", "THU", "MON", "SUN", "SAT" };

		HashSet<String> set1 = new HashSet<>(Arrays.asList(arr1));
		HashSet<String> set2 = new HashSet<>(Arrays.asList(arr2));

		set1.retainAll(set2);

		System.out.println(set1);
	}
}

Output

[THU, SAT, SUN, MON]