A brief way to write functions for arithmetic operations in Java 8

I want to summarize all the elements in List<Integer>using abbreviation.

In Scala I can write

val result = list.reduce(_ + _)

Is there a way to write this operation in such a compressed form in Java8? Or should I write like that?

int result = list.reduce((x,y) -> x + y));
+4
source share
3 answers

If you specifically want to use shortening, 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 summation is common, there are several ways to do this:

list.stream().mapToInt(x->x).sum();      // mapToInt makes an IntStream
list.stream().collect(summingInt(x->x)); // using a collector 
+7
source

You can use the predefined sum()from IntStream:

int result = list.stream().mapToInt(Integer::intValue).sum();
+3
source

, ((x,y) -> x + y)), , .

Classes for box primitives have static methods that perform some of the arithmetic operations, although not all of them are available. Those that are present can be used with reference to a method, for example Integer::sum.

Another way is to define the function yourself and pass it to the method:

public static final BinaryOperator<Integer> SUM = Integer::sum;
...
list.reduce(SUM)

This method is a bit more concise on the site of use, but you can decide whether the advance payment is worth writing out all the functions that you need or not.

0
source

All Articles