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 =
.filter(e -> e.getValue() > 1)
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.