Assume a list:
List<String> items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "grape");
Using Collectors.groupingBy + filter
Set<String> duplicates = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(duplicates);
Output:
[apple, banana]
Summary:
Collectors.groupingBy(Function.identity(), Collectors.counting())counts occurrences of each element..filter(e -> e.getValue() > 1)selects only duplicates..map(Map.Entry::getKey)extracts the duplicate values.- Result is a
Setof duplicate elements.
