I want to sum all elements in List<Integer>
via reduce.
In Scala I can write
val result = list.reduce(_ + _)
Is there a way to write this operation in such a concise way in Java8? Or should I write it this way?
int result = list.reduce((x,y) -> x + y));
If you specifically want to use reduce, this will do:
list.stream().reduce(0, Integer::sum); // will return zero if list is empty
list.stream().reduce(Integer::sum).get(); // will throw an exception if list is empty
Since summing is common, there are several ways to do it:
list.stream().mapToInt(x->x).sum(); // mapToInt makes an IntStream
list.stream().collect(summingInt(x->x)); // using a collector
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