The best way to obtain statistics from a Stream
is to use the ...SummaryStatistics
classes. For a Stream<Double>
, this is DoubleSummaryStatistics
:
List<Double> doubles = getListOfDoubles();
DoubleSummaryStatistics stats = doubles.stream().collect(Collectors.summarizingDouble(Double::doubleValue));
System.out.println(stats.getAverage());
System.out.println(stats.getSum());
It is obtained by collecting the stream with the summarizingDouble
collector. This collector takes a ToDoubleFunction
as argument: it is a function which should return the double
to analyze.
Such statistics can be obtained for Integer
, Long
and Double
values.
Note that the general case of converting a Collection<Double>
to a DoubleStream
can be done with the code you already have:
List<Double> doubles = getListOfDoubles();
DoubleStream stream = doubles.stream().mapToDouble(Double::doubleValue);