Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection<Double> to DoubleStream [duplicate]

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?

like image 513
Anatrollik Avatar asked Sep 14 '15 12:09

Anatrollik


2 Answers

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);
like image 192
Tunaki Avatar answered Sep 24 '22 06:09

Tunaki


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.

like image 28
Konstantin Yovkov Avatar answered Sep 21 '22 06:09

Konstantin Yovkov