Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Stream.reduce(BinaryOperator<T> accumulator) initialized?

The following code works perfectly without the need to initialize the reduce operation.

int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a+b).get(); // sum = 5
int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a*b).get(); // sum = 6

How does it know that the first accumulator is a + so that it should initialize to a new sum = 0, and the second accumulator is a * so that it should initialize to a new sum = 1?

like image 839
Stav Alfi Avatar asked May 22 '17 20:05

Stav Alfi


1 Answers

1-argument reduce doesn't start with an identity value (0 or 1). It only operates on the values in your stream. If you look at the javadoc, it even shows the equivalent code:

 boolean foundAny = false;
 T result = null;
 for (T element : this stream) {
     if (!foundAny) {
         foundAny = true;
         result = element;
     }
     else
         result = accumulator.apply(result, element);
 }
 return foundAny ? Optional.of(result) : Optional.empty();
like image 79
Misha Avatar answered Nov 01 '22 14:11

Misha