Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator() on parallel stream guarantee encounter order?

Stream.of(a, b, c).parallel().map(Object::toString).iterator();

Is the returned iterator guaranteed to provide the values a, b, c in that order?

I'm aware toArray() and collect() guarantee collections with values in the correct order. Also, I'm not asking how to make a stream from an iterator.

like image 931
David Leston Avatar asked Jan 10 '18 20:01

David Leston


People also ask

Does parallel stream preserve order?

If our Stream is ordered, it doesn't matter whether our data is being processed sequentially or in parallel; the implementation will maintain the encounter order of the Stream.

Does stream ensure order?

If you have an ordered stream and perform operations which guarantee to maintain the order, it doesn't matter whether the stream is processed in parallel or sequential; the implementation will maintain the order.

Does Java stream Map preserve order?

Does Stream map maintain order? A parallel stream is performed one or more elements at a time. Thus the map() would preserve the encounter of the stream order but not the original List's order.

Is Parallelstream faster?

First, note that parallelism offers no benefits other than the possibility of faster execution when more cores are available. A parallel execution will always involve more work than a sequential one, because in addition to solving the problem, it also has to perform dispatching and coordinating of sub-tasks.


1 Answers

This is an oversight in the specification. If a stream has a defined encounter order, the intent was that its Iterator produce the elements in encounter order. If the stream has no defined encounter order, the Iterator will of course produce the elements in some order, but that order won't be defined.

I've filed bug JDK-8194952 to track the change to the specification.

It looks like others have crawled through enough of the implementation to show that it will indeed produce the elements in encounter order. In addition, our stream tests rely on this property. For example, the test for the toList collector asserts that the elements in the list are present in the same order as they are obtained from the stream's Iterator. So it's probably safe for you to rely on this behavior, even though it isn't formally specified (yet).

like image 109
Stuart Marks Avatar answered Oct 12 '22 02:10

Stuart Marks