Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out of the java.util.stream.Stream interfaces's two collect methods, is one of them poorly constructed?

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?

like image 867
Alanpatchi Avatar asked Feb 03 '18 07:02

Alanpatchi


1 Answers

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).

like image 95
fps Avatar answered Sep 21 '22 23:09

fps