Parallel Stream toArray 维护顺序

Parallel Stream toArray maintains order

我读到了有关维护输入列表顺序的并发收集器的信息。所以如果我对ArrayList使用Collectors,它可以保证有序的集合。
有序列表上的映射函数也保持顺序。
我在 toArray

中找不到任何关于订单保存的文档

Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example, IntStream.range(0,5).parallel().map(x -> x*2).toArray() must produce [0, 2, 4, 6, 8]), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.

也会

Stream.map(x->x).toArray()

生成有序结果?或者我应该使用收集器。

the documentation 的引用部分已经举例说明 maptoArray 都将保持相遇顺序。

当你浏览 Stream API documentation 时,你会发现它从来没有明确说明维持相遇顺序的操作,而是相反,它明确说明操作何时是 无序或根据有序状态有特殊政策。

  • 显然unordered()显式收回遭遇顺序
  • forEachfindAny不遵守相遇顺序
  • Stream.concat returns 一个无序流,如果两个输入流中至少有一个是无序的(一个有争议的行为,但事实就是如此)
  • Stream.generate() 生成无序流
  • skiplimittakeWhiledropWhile 尊重遇到的顺序,这可能会导致并行执行中的显着性能损失
  • distinct()sorted() 对于有序流是稳定的,distinct() 在流无序时可能具有更好的并行性能
  • 如果收集器是无序的,
  • collect(Collector) 可能表现为无序,如果收集器是并发的并且流是无序的,则操作将是并发的语句仅暗示了这一点 收集器是无序的。更多详情,请参考Collector documentation and the builtin collectors.

请注意,虽然操作 count()allMatchanyMatchnoneMatch 没有关于相遇顺序的声明,但这些操作的语义暗示结果根本不应该取决于相遇顺序。