Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A concise way to write functions for arithmetical operations in Java 8

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));
like image 578
Alexander Tokarev Avatar asked Dec 26 '22 02:12

Alexander Tokarev


1 Answers

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 
like image 183
Misha Avatar answered Dec 28 '22 07:12

Misha