从java 8中的并行流中收集 [英] collecting from parallel stream in java 8

查看:39
本文介绍了从java 8中的并行流中收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想接受一个输入并在其上应用并行流,然后我想输出为列表.输入可以是我们可以应用流的任何列表或任何集合.

I want to take an input and apply parallel stream on that, then I want output as list. Input could be any List or any collection on which we can apply streams.

我担心的是,如果我们想要输出作为映射它们,我们有一个来自 java 的选项,就像

My concerns here is that if we want output as map them we have an option from java is like

list.parallelStream().collect(Collectors.toConcurrentMap(args))

但是我看不到以线程安全的方式从并行流中收集以提供列表作为输出的选项.我在那里看到了另一个使用选项

But there is no option that I can see to collect from parallel stream in thread safe way to provide list as output. I see one more option there to use

list.parallelStream().collect(Collectors.toCollection(<并发实现>))

这样我们就可以在collect方法中提供各种并发实现.但我认为 java.util.concurrent 中只有 CopyOnWriteArrayList List 实现.我们可以在这里使用各种队列实现,但不会像列表那样.我的意思是我们可以通过变通方法来获取列表.

in this way we can provide various concurrent implementations in collect method. But I think there is only CopyOnWriteArrayList List implementation is present in java.util.concurrent. We could use various queue implementation here but those will not be like list. What I mean here is that we can workaround to get the list.

如果我希望输出为列表,您能否指导我最好的方法是什么?

Could you please guide me what is the best way if I want the output as list?

注意:我找不到与此相关的任何其他帖子,任何参考都会有所帮助.

Note: I could not find any other post related to this, any reference would be helpful.

推荐答案

用于接收正在收集的数据的 Collection 对象不需要是并发的.你可以给它一个简单的ArrayList.

The Collection object used to receive the data being collected does not need to be concurrent. You can give it a simple ArrayList.

这是因为来自并行流的值集合实际上并未收集到单个 Collection 对象中.每个线程将收集自己的数据,然后将所有子结果合并到一个最终的Collection对象中.

That is because the collection of values from a parallel stream is not actually collected into a single Collection object. Each thread will collect their own data, and then all sub-results will be merged into a single final Collection object.

这一切都在 Collector javadoc,Collector 是您提供给 collect() 方法:

This is all well-documented in the Collector javadoc, and the Collector is the parameter you're giving to the collect() method:

<R,A> R collect(Collector<? super T,A,R> collector)

这篇关于从java 8中的并行流中收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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