Search code examples
javacollections

Identify duplicates in a List


I have a List of type Integer eg:

[1, 1, 2, 3, 3, 3]

I would like a method to return all the duplicates eg:

[1, 3]

What is the best way to do this?


Solution

  • The method add of Set returns a boolean whether a value already exists (true if it does not exist, false if it already exists, see Set documentation).

    So just iterate through all the values:

    public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates) { 
        final Set<Integer> setToReturn = new HashSet<>(); 
        final Set<Integer> set1 = new HashSet<>();
             
        for (Integer yourInt : listContainingDuplicates) {
            if (!set1.add(yourInt)) {
                setToReturn.add(yourInt);
            }
        }
        return setToReturn;
    }