Java 8 Distinct by property

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

    Extending Stuart Marks's answer, this can be done in a shorter way and without a concurrent map (if you don't need parallel streams):

    public static  Predicate distinctByKey(Function keyExtractor) {
        final Set seen = new HashSet<>();
        return t -> seen.add(keyExtractor.apply(t));
    }
    
    
    

    Then call:

    persons.stream().filter(distinctByKey(p -> p.getName());
    

    提交回复
    热议问题