The shortest stream solution keeps a HashSet of values already seen and filters the elements whose add() call returns false, because add() returns false when the value is already in the set.
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateElements {
public static void main(String[] args) {
List<Integer> list = List.of(10, 15, 8, 49, 25, 98, 98, 32, 15, 98);
// 1. HashSet: add() returns false for a value seen before
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = list.stream()
.filter(n -> !seen.add(n))
.collect(Collectors.toCollection(java.util.LinkedHashSet::new));
System.out.println("Duplicates: " + duplicates);
// 2. Count each value, keep the ones that occur more than once
Map<Integer, Long> counts = list.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
counts.entrySet().stream()
.filter(e -> e.getValue() > 1)
.forEach(e -> System.out.println(e.getKey() + " occurs " + e.getValue() + " times"));
}
}Duplicates: [98, 15]
15 occurs 2 times
98 occurs 3 times
Collections.frequency(list, n) > 1 inside a filter also works, but it scans the whole list for every element, making it O(n²).
Offer the HashSet version first and the groupingBy version as the safe choice for parallel streams or when counts are needed.
A concise interview answer is
I stream the list and filter with !seen.add(n) on a HashSet, which keeps only values that were already seen, and collect them into a Set so each duplicate appears once. If I also need the counts, or the stream is parallel, I group with Collectors.counting() and keep entries with a count above one.
Last updated: 11 November 2026
Previous question: Given a list of integers, find all the numbers starting with 1 using streams.
Next question: Given a list of integers, find the first element using streams.