Java 8 Stream: groupingBy with multiple Collectors

后端 未结 4 766
野性不改
野性不改 2020-12-15 08:20

I want to use a Java 8 Stream and Group by one classifier but have multiple Collector functions. So when grouping, for example the average and the sum of one field (or maybe

4条回答
  •  余生分开走
    2020-12-15 09:09

    You could chain them,

    A collector can only produce one object, but this object can hold multiple values. You could return a Map for example where the map has an entry for each collector you are returning.

    You can use Collectors.of(HashMap::new, accumulator, combiner);

    Your accumulator would have a Map of Collectors where the keys of the Map produced matches the name of the Collector. Te combiner would need a way to combine multiple result esp when this is performed in parallel.


    Generally the built in collectors use a data type for complex results.

    From Collectors

    public static 
    Collector summarizingDouble(ToDoubleFunction mapper) {
        return new CollectorImpl(
                DoubleSummaryStatistics::new,
                (r, t) -> r.accept(mapper.applyAsDouble(t)),
                (l, r) -> { l.combine(r); return l; }, CH_ID);
    }
    

    and in its own class

    public class DoubleSummaryStatistics implements DoubleConsumer {
        private long count;
        private double sum;
        private double sumCompensation; // Low order bits of sum
        private double simpleSum; // Used to compute right sum for non-finite inputs
        private double min = Double.POSITIVE_INFINITY;
        private double max = Double.NEGATIVE_INFINITY;
    

提交回复
热议问题