Java 8 Distinct by property

后端 未结 29 2422
傲寒
傲寒 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:13

    There's a simpler approach using a TreeSet with a custom comparator.

    persons.stream()
        .collect(Collectors.toCollection(
          () -> new TreeSet((p1, p2) -> p1.getName().compareTo(p2.getName())) 
    ));
    

提交回复
热议问题