Java Collection How to - Find the duplicate values in two Arrays








Question

We would like to know how to find the duplicate values in two Arrays.

Answer

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/* www .  j  a  v a  2 s.  c  om*/
public class MainClass {

  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));

    elements = new String[] { "B", "D", "F", "G", "1", "2", "3", "4" };
    Set set2 = new HashSet(Arrays.asList(elements));

    set.retainAll(set2);

    System.out.println(set);
  }
}

The code above generates the following result.