Java Collection How to - Get duplicates from an array in efficient way








Question

We would like to know how to get duplicates from an array in efficient way.

Answer

import java.util.HashSet;
import java.util.Set;
//w w w  .j  a v  a2s .  com
public class Main {
  public static void main(String[] args) throws java.lang.Exception {
    int[] strArray = new int[] { 0,0,0, 1, 1, 2, 3, 1, 2, 3, 4, 2, 5, 4 };
    Set<Integer> duplicates = checkDuplicate(strArray);
    System.out.printf("Duplicates: %s\n", duplicates);
  }

  private static Set<Integer> checkDuplicate(int[] intArray) {
    Set<Integer> duplicates = new HashSet<Integer>();
    Set<Integer> tmp = new HashSet<Integer>();
    for (Integer i : intArray) {
      if (!tmp.add(i)) {
        duplicates.add(i);
      }
    }
    return duplicates;
  }
}

The code above generates the following result.