In java.util.stream.Stream interface,
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
the combiner is a BiConsumer<R, R>
, whereas in
<R, A> R collect(Collector<? super T, A, R> collector);
the combiner is a BinaryOperator<A>
which is nothing but a BiFunction<A,A,A>
.
While the later form clearly defines what will be reference of the combined object after combining, the former form doesn't.
So how does any Stream implementation library know, what is the combined object in the former case?
In Java 9, the documentation of the Stream.collect(Supplier, BiConsumer, BiConsumer)
method has been updated and now it explicitly mentions that you should fold elements from the second result container into the first one:
combiner
- an associative, non-interfering, stateless function that accepts two partial result containers and merges them, which must be compatible with the accumulator function. The combiner function must fold the elements from the second result container into the first result container.
(Emphasis mine).
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