问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/31038180/sum-up-arraylistdouble-via-java-stream