Hello! Does `.forEach{it->}` guarantee the orig...
# getting-started
u
Hello! Does
.forEach{it->}
guarantee the original sequence during execution?
👌 2
g
yes
Though not all collections preserve order
u
Thanks! This seems to be different from the
stream().forEach()
of
java
g
right
This seems to be different from the
stream().forEach()
of
java
I believe it’s not different except if you use parallel stream
It’s not different on practice, but order is not specified (and parallel stream is an example where forEach will not executed in the same order)_
So I would say that you should first be sure about what kind forEach you are talking about, Collection.forEach ( either Java and Kotlin extension) just use iterator order and order of forEach will be the same as order of this collection iterator implementation
v
It's actually exactly the same as for
stream().forEach()
in Java. If the Stream is ordered and sequential,
forEach
will preserve the order. If the stream is unordered or parallel, order might not be preserved. Same for
forEach
in Kotlin. If the collection you run it on preserves order,
forEach
preserves order too, if no, then not.
g
Parallel stream is still quite a different case
v
Ah, well, actually
forEach
does have no guarantee even for ordered sequential stream, but there the order usually is preserved. Forgot about
forEachOrdered
which adds this guarantee for ordered streams, no matter whether sequential or parallel.