Java 8 Distinct by property

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

    Maybe will be useful for somebody. I had a little bit another requirement. Having list of objects A from 3rd party remove all which have same A.b field for same A.id (multiple A object with same A.id in list). Stream partition answer by Tagir Valeev inspired me to use custom Collector which returns Map>. Simple flatMap will do the rest.

     public static  Collector>> groupingDistinctBy(Function keyFunction, Function distinctFunction) {
        return groupingBy(keyFunction, Collector.of((Supplier>) HashMap::new,
                (map, error) -> map.putIfAbsent(distinctFunction.apply(error), error),
                (left, right) -> {
                    left.putAll(right);
                    return left;
                }, map -> new ArrayList<>(map.values()),
                Collector.Characteristics.UNORDERED)); }
    

提交回复
热议问题