collecting from parallel stream in java 8

后端 未结 2 1269
独厮守ぢ
独厮守ぢ 2020-12-29 22:58

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 co

2条回答
  •  不思量自难忘°
    2020-12-29 23:57

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

提交回复
热议问题