为什么我可以收集任意大数组的并行流,但不能收集顺序流?
2022-09-04 21:34:49
在回答这个问题时,我遇到了一个奇特的功能。下面的代码按照我的假设工作(现有数组中的前两个值将被覆盖):
Integer[] newArray = Stream.of(7, 8)
.parallel()
.toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});
System.out.println(Arrays.toString(newArray));
输出:
[7, 8, 3, 4, 5, 6]
但是,使用顺序流尝试此操作会引发:IllegalStateException
Integer[] newArray = Stream.of(7, 8)
.toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});
System.out.println(Arrays.toString(newArray));
输出:
Exception in thread "main" java.lang.IllegalStateException: Begin size 2 is not equal to fixed size 6
at java.base/java.util.stream.Nodes$FixedNodeBuilder.begin(Nodes.java:1222)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
at test/test.Test.main(Test.java:30)
我很好奇为什么顺序流不会像并行流那样覆盖数组的元素。我搜索了一下,无法找到有关此的文档,但我假设它存在于某个地方。