collecting from parallel stream in java 8(从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中的并行流中收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从java 8中的并行流中收集
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01