Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. List — forEach() / forEachIndexed()

List — forEach() / forEachIndexed()

Kotlin's forEach() executes a lambda for each element in a list. forEachIndexed() lets you receive both the index and the element at the same time. These are the fundamental methods for iteration.

Syntax

val fruits = listOf("Apple", "Banana", "Orange")

// forEach — executes a block for each element.
fruits.forEach { println(it) }

// forEachIndexed — also provides the index.
fruits.forEachIndexed { index, fruit ->
    println("$index: $fruit")
}

// Equivalent using a for loop.
for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}

Method List

MethodDescription
list.forEach { it }Executes a lambda for each element. Returns no value (Unit).
list.forEachIndexed { i, v -> }Executes a lambda with the index and element as arguments.
list.withIndex()Returns a list of index-element pairs (IndexedValue).
list.onEach { it }Same as forEach, but returns the original collection itself (chainable).
map.forEach { (k, v) -> }Receives the key and value of a map entry as separate parameters.

Sample Code

data class Student(val name: String, val score: Int)

fun main() {
    val students = listOf(
        Student("Alice", 85),
        Student("Bob", 72),
        Student("Carol", 91),
        Student("Dave", 68)
    )

    // Basic forEach
    println("=== Score List ===")
    students.forEach { student ->
        println("${student.name}: ${student.score} pts")
    }

    println()

    // Numbered output with forEachIndexed
    println("=== Numbered ===")
    students.forEachIndexed { index, student ->
        val rank = index + 1
        println("$rank. ${student.name}: ${student.score} pts")
    }

    println()

    // forEach on a map (destructuring key and value)
    val capitals = mapOf("Japan" to "Tokyo", "France" to "Paris", "USA" to "Washington D.C.")
    println("=== Capitals ===")
    capitals.forEach { (country, capital) ->
        println("Capital of $country: $capital")
    }

    println()

    // onEach — same as forEach but chainable.
    val names = students
        .onEach { println("Processing: ${it.name}") }
        .map { it.name }
    println("Name list: $names")

    println()

    // for loop with withIndex
    println("=== withIndex ===")
    for ((i, s) in students.withIndex()) {
        println("[$i] ${s.name}")
    }
}

Overview

Use forEach() for operations with side effects, such as logging or writing to a database. When you need the transformed results, use map(); when you need to filter elements by a condition, use filter() — these make your intent clearer.

To exit a forEach loop early, use return@forEach to return from the lambda (a plain return would return from the enclosing function). To break out of the loop entirely, use a for loop with break.

For basic list operations, see List — Creating / listOf() / mutableListOf(). For filtering and transformation, see List — filter() / map().

If you find any errors or copyright issues, please .