java怎么并行发list中的数据,在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.

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

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.

解决方案

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

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.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值