forEach defined in Iterable , and Javadoc says:
Unless otherwise specified by the implementation class, actions are performed in iteration order (if the iteration order is specified).
Now List.iterator() says:
Returns an iterator over the items in this list in the correct sequence.
Thus, by default, you should expect forEach list items in the correct sequence, unless the list implementation has a different iterator implementation.
According to Stream.forEach Javadoc tells you that you should not rely on an order:
The behavior of this operation is clearly non-deterministic. For parallel flow pipelines, this operation does not guarantee to respect the flow meeting order, as it sacrifices the benefits of parallelism.
but there is also Stream.forEachOrdered :
Performs an action for each element of this stream, in a collision, the order of the stream, if the stream has a specific order of meetings.
wero source share