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()
?
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.
forEach() calls a provided callbackFn function once for each element in an array in ascending index 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With