https://kotlinlang.org logo
#getting-started
Title
# getting-started
u

毛小川

03/01/2022, 9:08 AM
Hello! Does
.forEach{it->}
guarantee the original sequence during execution?
👌 2
g

gildor

03/01/2022, 9:10 AM
yes
Though not all collections preserve order
u

毛小川

03/01/2022, 9:14 AM
Thanks! This seems to be different from the
stream().forEach()
of
java
g

gildor

03/01/2022, 9:20 AM
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

Vampire

03/01/2022, 10:53 AM
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

gildor

03/01/2022, 1:12 PM
Parallel stream is still quite a different case
v

Vampire

03/01/2022, 1:25 PM
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.
3 Views