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

Viewed 2226

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?

3 Answers
Related