Java 8 Distinct by property

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

    You can use groupingBy collector:

    persons.collect(Collectors.groupingBy(p -> p.getName())).values().forEach(t -> System.out.println(t.get(0).getId()));
    

    If you want to have another stream you can use this:

    persons.collect(Collectors.groupingBy(p -> p.getName())).values().stream().map(l -> (l.get(0)));
    

提交回复
热议问题