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

蹲街弑〆低调 提交于 2020-05-25 06:09:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!