iterator() on parallel stream guarantee encounter order?

David Leston :
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.

Stuart Marks :

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).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=434546&siteId=1