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
If you want to List of Persons following would be the simple way
Set set = new HashSet<>(persons.size());
persons.stream().filter(p -> set.add(p.getName())).collect(Collectors.toList());
Additionally, if you want to find distinct or unique list of names, not Person , you can do using following two method as well.
Method 1: using distinct
persons.stream().map(x->x.getName()).distinct.collect(Collectors.toList());
Method 2: using HashSet
Set set = new HashSet<>();
set.addAll(person.stream().map(x->x.getName()).collect(Collectors.toList()));