Java 8 Distinct by property

后端 未结 29 1782
傲寒
傲寒 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 22:55

    An alternative would be to place the persons in a map using the name as a key:

    persons.collect(Collectors.toMap(Person::getName, p -> p, (p, q) -> p)).values();
    

    Note that the Person that is kept, in case of a duplicate name, will be the first encontered.

提交回复
热议问题