12

I googled this and also tried to find documentation about it but failed to do so.

Question is simple. I have a List let's say foo. if I do

foo.forEach(this::doSomething) and use the same line again for the same foo would I have the order of the iteration same each time?

If yes, what about foo.stream().forEach()?

2
  • It'd be pretty weird if the order of iteration of a sequential data structure wasn't... sequential. Commented May 14, 2016 at 11:48
  • 3
    General rule with libraries: if it's not explicitly documented, then don't expect it to behave as you think or consistently at all. Commented May 14, 2016 at 11:49

1 Answer 1

21

forEach is defined in Iterable and the Javadoc says:

Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified).

Now List.iterator() says:

Returns an iterator over the elements in this list in proper sequence.

So by default you should expect that forEach enumerates the elements in proper sequence - unless an list implementation has a differing iterator implementation.


According Stream.forEach the Javadoc tells you that you should not rely on an order:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

but there is also Stream.forEachOrdered:

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

Sign up to request clarification or add additional context in comments.

1 Comment

sorry but in that case parallelStream().forEach() would also return in sequence?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.