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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With