Collecting Statistics in Java8

Viewed 553

I would like to collect statistics after grouping a set of data, but i don't know if it is possible

Map<String, DoubleSummaryStatistics> menuStatistics =

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

because I have some compilation problems:

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 Answers

You need to use Collectors.summarizingDouble(), assuming your class (the element type of the Stream) has some double property for which you want to calculate the statistics:

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