用Java8收集统计信息

时间:2018-09-20 10:06:23

标签: java lambda java-8 functional-programming java-stream

我想对一组数据进行分组后收集统计信息,但我不知道是否可能

Map<String, DoubleSummaryStatistics> menuStatistics =

                menuPrices.parallelStream()
                        .collect(Collectors.groupingBy(cp -> dt1.format(cp.getUpdateDate())),
                                Collector.of(DoubleSummaryStatistics::new));

因为我有一些编译问题:

Multiple markers at this line
    - The method of(Supplier<R>, BiConsumer<R,T>, BinaryOperator<R>, Collector.Characteristics...) in the type Collector is not applicable for the arguments 
     (DoubleSummaryStatistics::new)
    - The constructed object of type DoubleSummaryStatistics is incompatible with the descriptor's return type: R

1 个答案:

答案 0 :(得分:3)

您需要使用Collectors.summarizingDouble(),假设您的类(Stream的元素类型)具有一些double属性,您要为其计算统计信息:

Map<String, DoubleSummaryStatistics>
    menuStatistics =
        menuPrices.parallelStream()
                  .collect(Collectors.groupingBy(cp -> dt1.format(cp.getUpdateDate()),
                           Collectors.summarizingDouble(cp -> cp.getSomeDoubleValue())));