The 30 second answer
I call distinct and collect to a list. On ordered streams the first occurrence is kept. If uniqueness is by a field like email, I toMap with that key, keep the first value on collision, and use LinkedHashMap to preserve order.
Could you say this in an interview?
List<T> unique = list.stream().distinct().toList();Keeps the first occurrence for ordered streams (stable).
By a key (for example unique by email):
Collection<Employee> uniqueByEmail = emps.stream()
.collect(Collectors.toMap(
Employee::email,
Function.identity(),
(a, b) -> a,
LinkedHashMap::new))
.values();
Sources (2)
- Stream.distinctdocs.oracle.com
- Collectors.toMapdocs.oracle.com