Java 8 Distinct by property

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

    My approach to this is to group all the objects with same property together, then cut short the groups to size of 1 and then finally collect them as a List.

      List listWithDistinctPersons =   persons.stream()
                //operators to remove duplicates based on person name
                .collect(Collectors.groupingBy(p -> p.getName()))
                .values()
                .stream()
                //cut short the groups to size of 1
                .flatMap(group -> group.stream().limit(1))
                //collect distinct users as list
                .collect(Collectors.toList());
    

提交回复
热议问题