关于收集(供应商,累加器,合并器) [英] About collect (supplier, accumulator, combiner)

查看:459
本文介绍了关于收集(供应商,累加器,合并器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白以下方法的第三个参数的效用:

 < R> R collect(供应商< R>供应商,
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 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.

这篇关于关于收集(供应商,累加器,合并器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆