Java 8 Stream: average and count at once

nicmon :

I have a DoubleStream which has been calculated from a very time consuming function, and I want to calculate the Average and Count of its elements at the same time.

The Problem is I do not want to calculate the DoubleStream twice because of the mentioned time consuming calculation of values. I want to get the value of both Average and Count from one lambda expression.

I have tried everything with collect and map and so on but had no success.

    final long count = products.stream()
            .mapToDouble(this::timeConsumingCalculateRating)
            .filter(rating -> rating > 0.0D)
            .count();

    final double averageRating = products.stream()
            .mapToDouble(this::timeConsumingCalculateRating)
            .filter(rating -> rating > 0.0D)
            .average()
            .orElse(0.0D);

any help is highly appreciated.

Eran :

Use summaryStatistics():

DoubleSummaryStatistics stats = products.stream()
            .mapToDouble(this::timeConsumingCalculateRating)
            .filter(rating -> rating > 0.0D)
            .summaryStatistics();
long count = stats.getCount();
double averageRating = stats.getAverage();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127092&siteId=1