Running the following stream example in Java8:
System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.reduce("", (s1, s2) -> s1 + "/" + s2)
);
yields:
/a/b/c/d/e/f
Which is - of course - no surprise. Due to http://docs.oracle.com/javase/8/docs/api/index.html?overview-summary.html it shouldn't matter whether the stream is executed sequentially or parallel:
Except for operations identified as explicitly nondeterministic, such as findAny(), whether a stream executes sequentially or in parallel should not change the result of the computation.
AFAIK reduce()
is deterministic and (s1, s2) -> s1 + "/" + s2
is associative, so that adding parallel()
should yield the same result:
System.out.println(Stream
.of("a", "b", "c", "d", "e", "f")
.parallel()
.reduce("", (s1, s2) -> s1 + "/" + s2)
);
However the result on my machine is:
/a//b//c//d//e//f
What's wrong here?
BTW: using (the preferred) .collect(Collectors.joining("/"))
instead of reduce(...)
yields the same result a/b/c/d/e/f
for sequential and parallel execution.
JVM details:
java.specification.version: 1.8
java.version: 1.8.0_31
java.vm.version: 25.31-b07
java.runtime.version: 1.8.0_31-b13
See Question&Answers more detail:os