Java 8 Distinct by property

后端 未结 29 2260
傲寒
傲寒 2020-11-21 22:35

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

29条回答
  •  一整个雨季
    2020-11-21 23:09

    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()));
    

提交回复
热议问题