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.
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:
Sources (0)
See inline citations in the answer above.