How do I loop through collections using for, foreach and indices in Kotlin?

In Kotlin, you can loop through collections in several common ways depending on whether you need the element, the index, or both.

1. Using for

Use for when you want a simple, readable loop over elements.

val names = listOf("Alice", "Bob", "Charlie")

for (name in names) {
    println(name)
}

Output:

Alice
Bob
Charlie

This works with many Kotlin types, including:

val numbers = arrayOf(1, 2, 3)

for (number in numbers) {
    println(number)
}

2. Using forEach

Use forEach when you prefer a functional style.

val names = listOf("Alice", "Bob", "Charlie")

names.forEach { name ->
    println(name)
}

If the lambda has only one parameter, you can use it:

names.forEach {
    println(it)
}

forEach is useful for concise operations, but a regular for loop is often clearer if you need break, continue, or more complex control flow.


3. Looping with indices

Use indices when you need the index of each element.

val names = listOf("Alice", "Bob", "Charlie")

for (i in names.indices) {
    println("Index $i: ${names[i]}")
}

Output:

Index 0: Alice
Index 1: Bob
Index 2: Charlie

indices gives the valid index range for the collection, such as 0..lastIndex.


4. Using withIndex

If you need both the index and the value, withIndex() is often cleaner than indexing manually.

val names = listOf("Alice", "Bob", "Charlie")

for ((index, name) in names.withIndex()) {
    println("Index $index: $name")
}

5. Using forEachIndexed

The forEach equivalent for index + value is forEachIndexed.

val names = listOf("Alice", "Bob", "Charlie")

names.forEachIndexed { index, name ->
    println("Index $index: $name")
}

Summary

val items = listOf("A", "B", "C")

// Element only
for (item in items) {
    println(item)
}

// Element only, functional style
items.forEach { item ->
    println(item)
}

// Index only / index-based access
for (i in items.indices) {
    println("items[$i] = ${items[i]}")
}

// Index and value
for ((index, item) in items.withIndex()) {
    println("$index -> $item")
}

// Index and value, functional style
items.forEachIndexed { index, item ->
    println("$index -> $item")
}

Use:

  • for (item in items) for simple iteration
  • items.forEach { ... } for concise functional-style iteration
  • items.indices when you need index-based access
  • withIndex() or forEachIndexed when you need both index and value