does for respect order in kotlin? `for (item in it...
# android
p
does for respect order in kotlin?
for (item in items) { }
e
same as Java: depends on
items
iteration order
many collections have well-defined orders, some do not
🙌 1
b
I'll make the argument that if you're using for in that context that you shouldn't really care about the ordering anyway. If you do care about the ordering I'd say forEachIndexed is a better way to go - even if you don't care about the ordering necessarily but want to convey that the order of the items is important to future developers/self I think forEachIndexed is a nice reminder that the ordering is important - but that's more philosophical than is potentially useful 😆
👎🏼 1
👎🏾 1
👎 4
e
I do not agree. it is fine to expect that an ordinary
List
iterates in order, whether you use `for`/`forEach`/`forEachIndexed`, so choose whatever is appropriate for the task at hand. but
forEachIndexed
will give you an
index
on anything, even things which are not indexable, such as
Set
. do not use it without reason.
☝🏼 1
☝🏾 1
☝️ 3
b
all good points
p
so, coming back to my question, if I do this:
for (item in items) { }
... will it respect the order in items?
e
and as I said, it depends on what is
items
p
?
what u mean?
for example this: items.add(1,2,3,4,5,6)
or this: items.add("one","two", "three")
e
if
items
is a
List
then it is ordered. if
items
is a
Set
then it may or may not have a consistent order.
p
don't know what is a Set
I always work with lists, for example, mutableListOf()
is that OK i supose then
thank you!
k
In Kotlin, the for loop respects the order of items only if the collection type preserves it. Ordered collections like List and LinkedHashSet keep their order in a loop, while unordered ones like HashSet don’t guarantee any specific order.
Copy code
// Ordered collection: List
val orderedItems = listOf("apple", "banana", "cherry")
for (item in orderedItems) {
    println(item) // Output: apple, banana, cherry (in order)
}

// Unordered collection: HashSet
val unorderedItems = hashSetOf("apple", "banana", "cherry")
for (item in unorderedItems) {
    println(item) // Output: No guaranteed order, may vary
}