This post will discuss how to report all duplicates in an array in Java.

1. Using a Set

The idea is to iterate through the array and keep track of the encountered items in a Set. If an element is seen before, mark it as duplicate and report all duplicates at the end of the loop. This can be easily done using Java 8 Stream:

Download  Run Code

Output:

[3, 4]

 
Here’s a version without using streams:

Download  Run Code

Output:

[3, 4]

2. Using a List

Another solution is to convert the array to a list and filter duplicates in the list using Stream API. The following code uses the Collections.frequency() method to get the frequency of each element in the collection.

Download  Run Code

Output:

[3, 4]

3. Using a Frequency Map

The above implementation is not efficient, as it is getting the frequency of each element. We can improve its performance by creating a frequency map and then filtering the values having a frequency more than 1.

Download  Run Code

Output:

[3, 4]

 
Here’s a version without using streams:

Download  Run Code

Output:

[3, 4]

That’s all about finding all duplicates in an array in Java.