Java 8 Distinct by property

后端 未结 29 1829
傲寒
傲寒 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

    Consider distinct to be a stateful filter. Here is a function that returns a predicate that maintains state about what it's seen previously, and that returns whether the given element was seen for the first time:

    public static  Predicate distinctByKey(Function keyExtractor) {
        Set seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }
    
    
    

    Then you can write:

    persons.stream().filter(distinctByKey(Person::getName))
    

    Note that if the stream is ordered and is run in parallel, this will preserve an arbitrary element from among the duplicates, instead of the first one, as distinct() does.

    (This is essentially the same as my answer to this question: Java Lambda Stream Distinct() on arbitrary key?)

    提交回复
    热议问题