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

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

问题描述

我想获取输入并对其应用并行流,然后我想将输出作为列表。输入可以是我们可以应用流的任何List或任何集合。

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(< Concurrent Implementation> ))

这样我们可以在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.

这一点都在 收集器 javadoc,收集器是您给予的参数 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天全站免登陆