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?
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() .
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).
1. Can we reuse stream? No. Java streams, once consumed, can not be reused by default.
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
.
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