From answering this question, I ran into a peculiar feature. The following code works as I assumed it would (the first two values within the existing array would be overridden):
Integer[] newArray = Stream.of(7, 8)
.parallel()
.toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});
System.out.println(Arrays.toString(newArray));
Output:
[7, 8, 3, 4, 5, 6]
However, attempting this with a sequential stream throws an IllegalStateException
:
Integer[] newArray = Stream.of(7, 8)
.toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});
System.out.println(Arrays.toString(newArray));
Output:
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)
I'm curious as to why the sequential stream does not overwrite elements of the array as the parallel stream does. I searched around a bit and was not able to find documentation regarding this, but I assume it exists somewhere.
The generator
function is required to produce "a new array of the desired type and the provided length." If you don't comply with the spec, behavior is undefined.
来源:https://stackoverflow.com/questions/49760818/why-can-i-collect-a-parallel-stream-to-an-arbitrarily-large-array-but-not-a-sequ