Java 8 Stream: groupingBy with multiple Collectors

后端 未结 4 760
野性不改
野性不改 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 08:58

    Instead of chaining the collectors, you should build an abstraction which is an aggregator of collectors: implement the Collector interface with a class which accepts a list of collectors and delegates each method invocation to each of them. Then, in the end, you return new Data() with all the results the nested collectors produced.

    You can avoid creating a custom class with all the method declarations by making use of Collector.of(supplier, accumulator, combiner, finisher, Collector.Characteristics... characteristics) The finisher lambda will call the finisher of each nested collector, then return the Data instance.

提交回复
热议问题