Java 8 Distinct by property

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

    Another solution, using Set. May not be the ideal solution, but it works

    Set set = new HashSet<>(persons.size());
    persons.stream().filter(p -> set.add(p.getName())).collect(Collectors.toList());
    

    Or if you can modify the original list, you can use removeIf method

    persons.removeIf(p -> !set.add(p.getName()));
    

提交回复
热议问题