java – Java 8 Distinguished by properties

Maybe it will be useful for someone. I had another small requirement. The list of objects A third-party removes all those that have the same field A.b for the same (more items A with the same in the list). Partition stream answer of Tagir Valeev inspired me to use Collector custom that 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) -> {
                return left;
            }, map -> new ArrayList<>(map.values()),
            Collector.Characteristics.UNORDERED)); }

Leave a comment