16

I do not understand the utility of the third parameter of the following method:

<R> R collect(Supplier<R> supplier,
              BiConsumer<R,? super T> accumulator,
              BiConsumer<R,R> combiner)

from javaDoc:

This produces a result equivalent to:

 R result = supplier.get();
 for (T element : this stream)
     accumulator.accept(result, element);
 return result;

as you can see the parameter combiner is not used. For example, the following will accumulate strings into an ArrayList:

 List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
                                            ArrayList::addAll);

but I expected this:

List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add );
Eran
  • 387,369
  • 54
  • 702
  • 768
Kachna
  • 2,921
  • 2
  • 20
  • 34

1 Answers1

23

The combiner is used when your Stream is parallel, since in that case several threads collect elements of the Stream into sub-lists of the final output ArrayList, and these sub-lists have to be combined to produce the final ArrayList.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • If parallelly processed, then the original stream order won't be guaranteed in the result after combining. Right? – GC001 Aug 01 '17 at 21:24
  • @Chen I believe that depends on the combiner passed to `collect`. The combiner can keep the original order. – Eran Aug 02 '17 at 06:54
  • @Chen You are right. Order wont be guaranteed. The assumption for the combiner is, combiner operation should be associative e.g. a+(b+c) = (a+b)+c – Aniket Rangrej Mar 30 '19 at 19:49