Stav Alfi Stav Alfi - 1 year ago 40
Java Question

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

The following code works perfectly without the need to initialize it.

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 ?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download