Java 8, Streams to find the duplicate elements using Stream API

By | March 23, 2023

To find the duplicate elements from a collection using Java 8 streams, you can use the Collectors.groupingBy method to group elements by their value, and then filter the resulting map to include only those entries with more than one value. Here’s an example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 1, 6, 7, 5);

Map<Integer, Long> duplicates =

               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))



               .filter(e -> e.getValue() > 1)

               .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

System.out.println(“Duplicate elements: ” + duplicates.keySet());

In the above example, we first create a list of Integer objects. We then call the stream method on the list to create a stream of integers. Next, we call the Collectors.groupingBy method, passing in Function.identity() as a classifier function, which groups the elements in the stream by their value. The groupingBy method returns a Map<Integer, List<Integer>> where each key corresponds to an element in the stream, and the value is a list of all elements that have that value. We then use the Collectors.counting() method as a downstream collector to count the number of occurrences of each element.

We then call the entrySet method on the resulting map to get a set of key-value pairs. We then call the stream method on the set, and use the filter method to include only those entries whose value is greater than one (i.e., duplicates). Finally, we collect the filtered entries into a new map using the toMap method, with the original keys as the keys in the new map, and the count of occurrences as the values.

Note that we’re using a Map<Integer, Long> to store the count of occurrences for each element. The Long type is used because the counting method returns a long value. If you don’t need to store the count of occurrences, you can modify the code to simply store the duplicate elements themselves by changing the type of the resulting map to Map<Integer, List<Integer>> and using Collectors.mapping(Function.identity(), Collectors.toList()) as a downstream collector in the groupingBy method.

Leave a Reply

Your email address will not be published. Required fields are marked *