0 votes
1 view
in Java by (3.4k points)

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of Person object and I want to remove people with the same name,


Will use the default equality check for a Person object, so I need something like,

persons.stream().distinct(p -> p.getName());

Unfortunately, the distinct() method has no such overload. Without modifying the equality check inside the Person class is it possible to do this succinctly?

1 Answer

0 votes
by (26.5k points)

Examine separately to be a stateful filter. Hither is a function that reverses a word that keeps state regarding what it's seen earlier, and that reflects whether the presented element was observed for the first time:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {

Set<Object> seen = ConcurrentHashMap.newKeySet();

return t -> seen.add(keyExtractor.apply(t));


Then you can print:


Note that if the stream is established and is operated in similarity, this will defend an arbitrary part from between the duplicates, preferably of the first one, as distinct() does.