Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up ArrayList<Double> via Java Stream [duplicate]

Im trying to Figure out how to Sum up all the elements of an 'ArrayList'.

Ive tried already:

 double totalevent = myList.stream().mapToDouble(f -> f).sum();

while myList is a ArrayList<Double>.

is there a way to do it without the useless mapToDouble function?

like image 966
Joel Avatar asked Jun 24 '15 22:06

Joel


People also ask

How do you sum a stream in Java?

Using Stream.collect() The second method for calculating the sum of a list of integers is by using the collect() terminal operation: List<Integer> integers = Arrays. asList(1, 2, 3, 4, 5); Integer sum = integers. stream() .

How do you sum a double in Java?

Java Double sum() Method Java sum() method is a part of the Double class of the java. lang package. This method returns the numerical sum of the double values passed as arguments (i.e simply adds the two numbers passed as argument in accordance with the + operator).

Can you reuse a Java stream?

1. Can we reuse stream? No. Java streams, once consumed, can not be reused by default.


1 Answers

The mapToDouble call is not useless: it performs an implicit unboxing. Actually it's the same as

double totalevent = myList.stream().mapToDouble(f -> f.doubleValue()).sum();

Or

double totalevent = myList.stream().mapToDouble(Double::doubleValue).sum();

Alternatively you can use summingDouble collector, but it's not a big difference:

double totalevent = myList.stream().collect(summingDouble(f -> f));

In my StreamEx library you can construct a DoubleStream directly from Collection<Double>:

double totalevent = DoubleStreamEx.of(myList).sum();

However internally it also uses mapToDouble.

like image 147
Tagir Valeev Avatar answered Nov 19 '22 14:11

Tagir Valeev