The question is about java.util.stream.Stream.reduce(U identity,BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
method.
One of the requirements is that the combiner function must be compatible with the accumulator function; for all u and t, the following must hold:
combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) (*)
If the combiner
and accumulator
are the same, the above equality is automatically true.
A BinaryOperator
is actually extending BiFunction, therefore I can use it when BiFunction
is required. If U and T are identical, the following is always legal:
operator<T> op = (x,y) -> something;
stream.reduce(id, op, op);
Of course, one cannot always use the combiner
as acumulator
since, in the general case, they serve for different purposes and are different Java types.
My question
Is there an example of stream reduction with distinct combiner
and accumulator
?
Also, I'm not interested in trivial examples, but natural examples that I can encounter in practice while doing reduction on parallel streams.
For trivial examples, there are many tutorials, like this one
Why am I asking this question
Basically, the reason this reduction method exists is for parallel streams. It seems to me the condition (*) is so strong that, in practice, it renders this reduction useless since rarely the reduction operations fulfill it.