Java 8 Distinct by property

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

    I made a generic version:

    private  Collector> distinctByKey(Function keyExtractor) {
        return Collectors.collectingAndThen(
                toMap(
                        keyExtractor,
                        t -> t,
                        (t1, t2) -> t1
                ),
                (Map map) -> map.values().stream()
        );
    }
    

    An exemple:

    Stream.of(new Person("Jean"), 
              new Person("Jean"),
              new Person("Paul")
    )
        .filter(...)
        .collect(distinctByKey(Person::getName)) // return a stream of Person with 2 elements, jean and Paul
        .map(...)
        .collect(toList())
    

提交回复
热议问题