Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About collect (supplier, accumulator, combiner) [duplicate]

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 );
like image 473
Kachna Avatar asked Jul 21 '15 07:07

Kachna


1 Answers

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.

like image 158
Eran Avatar answered Oct 31 '22 09:10

Eran