Java and Spring Level 1 This level · 26 of 105
Medium java streams

Find duplicate elements in a list

The 30 second answer

I group elements by identity, count them, and keep keys whose count is greater than one. That stays pure and works with parallel streams. The HashSet add trick is shorter but uses a stateful lambda, so I avoid it unless the stream is clearly sequential. Either way I mention equals and hashCode have to be correct.

Could you say this in an interview?

Stateful shortcut (sequential only):

Set<T> seen = new HashSet<>();
Set<T> dups = list.stream()
    .filter(x -> !seen.add(x))
    .collect(Collectors.toSet());

This uses a stateful lambda. The package summary warns that behavioral parameters should be stateless, and this breaks under parallel().

Cleaner pure version:

Set<T> dups = list.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    .entrySet().stream()
    .filter(e -> e.getValue() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());

Both are O(n) expected time with a good hashCode. They rely on correct equals / hashCode.

Alternate interview scenarios

"Find the duplicates with Collections.frequency."

It reads well and has no stateful lambda:

var list = List.of(3, 1, 3, 2, 1, 5);
var dups = list.stream()
    .filter(x -> Collections.frequency(list, x) > 1)
    .collect(Collectors.toSet());
// [1, 3]

The catch is the cost. Collections.frequency returns the number of elements equal to the object, so it has to scan the whole collection on every call. Calling it once per element makes the pipeline O(n²) time. The groupingBy and counting version above, or the HashSet add trick, counts in one pass with O(n) expected time and O(n) space. I would only keep frequency for a tiny list, and say why. [Opinion — standard complexity reasoning]

Sources (3)
  1. java.util.stream package (stateless behaviors)docs.oracle.com
  2. Collectorsdocs.oracle.com
  3. Collections.frequencydocs.oracle.com
Previous
Next