In other words, why does reduce require BinaryOperator, or BiFunction interface? Why doesn’t it use UnaryOperator, or Function interface instead?
What is the point of having two parameters as the input for the functional interface? (I know it’s for accumulation, but why doesn’t one parameter suffice?)
Advertisement
Answer
How would you compute a single value that depends on all the Stream
elements with a UnaryOperator
?
You can apply the UnaryOperator
on the first element of the Stream
.
Then you can apply the UnaryOperator
on the second element of the Stream
.
But you can’t combine the two results.
A BinaryOperator
can be applied on the first and second elements of the Stream
.
Then you can apply it on the intermediate result (of the first two elements) and the 3rd element of the Stream
, to get an intermediate result that depends on the first 3 elements, and so on… until you get a result that depends on all the elements.