Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
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,

persons.stream().distinct();

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 (46k 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:

persons.stream().filter(distinctByKey(Person::getName))

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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...