This post will discuss how to identify duplicates in a List in Java.

1. Using Set

A simple solution is to iterate through all values in the list and insert each element into a HashSet. If the current element already exists in the set, then it is a duplicate. You can collect all duplicates found in a new list.

This can be easily done using Java 8 Stream. Note that the solution uses the return value of the Set.add() method to determine if the value is already present in the set or not

Download  Run Code

Output:

[1, 3]

 
The above code is equivalent to the following code (for Java 7 and less):

Download  Run Code

Output:

[1, 3]

2. Using Collections.frequency() method

The simplest way is probably to count the frequency of each list element to determine if it is a duplicate or not. You can use the Collections.frequency() method for this, which returns the number of elements in the collection.

Here’s code using Stream API:

Download  Run Code

Output:

[1, 3]

 
This is equivalent to following:

Download  Run Code

Output:

[1, 3]

3. Using Collectors.groupingBy() function

The above solution calls the Collections.frequency() method for each element of the list. A better solution is to create a frequency map and use that to determine if an element is duplicated or not. The following Java 8 solution uses Streams to filter the items having the frequency of more than 1:

Download  Run Code

Output:

[1, 3]

That’s all about identifying duplicates in a List in Java.