Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is List.forEach ordered in Java?

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()?

like image 567
Sarp Kaya Avatar asked May 14 '16 11:05

Sarp Kaya


People also ask

Does forEach go in order Java?

Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.

Is forEach ordered?

forEach() calls a provided callbackFn function once for each element in an array in ascending index order.

Does a for each loop go in order?

The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages, especially array programming languages, does not have any particular order.


1 Answers

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.

like image 133
wero Avatar answered Oct 12 '22 10:10

wero