I'm looking for most elegant way to create DoubleStream (for using sum, average, etc.) from a List<Double>. At the moment I have such code:
List<Double> doubles = getListOfDoubles();
double sum = doubles.stream()
.mapToDouble(d -> d)
.sum();
Maybe anyone could suggest a shorter way?
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);
You can do (even it's not significantly shorter, but...):
double sum = doubles.stream().collect(Collectors.summingDouble(x -> x));
or
double sum = DoubleStream.of(doubles.stream().mapToDouble(x->x).toArray()).sum();
but the latter is more or less the same as your approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With