关于收集(供应商,累加器,合并器) [英] About collect (supplier, accumulator, combiner)
问题描述
我不明白以下方法的第三个参数的效用:
< R> R collect(供应商< R>供应商,
$ p来自
BiConsumer< R,?super T>累加器,
BiConsumer< R,R>组合器)
java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-rel =noreferrertitle =javaDoc> javaDoc
:
这产生的结果相当于:
R result = supplier.get();
for(T element:this stream)
accumulator.accept(result,element);
返回结果;
因为你可以看到参数
combiner
未使用。例如,以下内容将字符串累积到ArrayList中:List< String> asList = stringStream.collect(ArrayList :: new,ArrayList :: add,
ArrayList :: addAll);
但我期望这样:
列表与LT;字符串> asList = stringStream.collect(ArrayList :: new,ArrayList :: add);
解决方案
组合器$当
Stream
是并行时使用c $ c>,因为在这种情况下,有几个线程将Stream
的元素收集到最终输出的子列表ArrayList
,这些子列表必须合并以生成最终的ArrayList
。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 );
解决方案The
combiner
is used when yourStream
is parallel, since in that case several threads collect elements of theStream
into sub-lists of the final outputArrayList
, and these sub-lists have to be combined to produce the finalArrayList
.这篇关于关于收集(供应商,累加器,合并器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!