SoFunction
Updated on 2025-04-13

kotlin's function forEach example detailed explanation

In Kotlin,forEachIs a higher-order function that iterates through each element in a collection and performs specified operations on it. Its core feature isConcise, functional, suitable for scenarios where collections need to be traversed without returning values. Here are detailed instructions and examples:

1. Basic usage

1️⃣ Traversing the collection

val list = listOf("Apple", "Banana", "Orange")
// Use lambda expressions { fruit -> 
    println(fruit) 
}
// Simplify to `it` { println(it) }

2️⃣ traverse the array

val array = arrayOf(1, 2, 3)
 { println(it) }

3️⃣ Traversing Map

val map = mapOf("A" to 1, "B" to 2)
// traverse key-value pairs (Pair) { (key, value) ->
    println("$key -> $value")
}
// Or use `` and `` directly { println("${}: ${}") }

2. The difference from for loop

characteristic forEach forcycle
grammar Functional style, manipulating elements through lambda Traditional circular structure
Control flow not availablebreak/continue supportbreak/continue
returnBehavior Return from outer function by default (requires label control) Exit the current loop only
Applicable scenarios Simple traversal operation Scenarios where complex control flows or premature termination of loops are required

Example:returnBehavior

fun testForEach() {
    listOf(1, 2, 3).forEach {
        if (it == 2) return  // Exit the entire function directly!        println(it)
    }
    println("End") // Will not execute}
// Output:1

Use tag controlreturn

fun testForEachLabel() {
    listOf(1, 2, 3).forEach {
        if (it == 2) return@forEach  // Exit only the current lambda        println(it)
    }
    println("End") // Will execute}
// Output:1, 3, End

3. Advanced usage

1️⃣ traversal with index (combinedwithIndex

().forEach { (index, value) ->
    println("$index: $value")
}

2️⃣ Ignore parameters (using_

 { index, _ ->
    println("Index $index") // Ignore element values}

3️⃣ Chain call (combined with other higher-order functions)

 {  > 5 }
    .forEach { println(it) } // Filter first and then traverse

4. Things to note

Avoid side effects
forEachShould be used only for traversal,Do not modify external variables in it(Unless necessary).

// ❌ Not recommended: Modify external statusvar count = 0
 { count++ }
// ✅ Recommended: Use the `count()` functionval count = 

Don't modify the collection itself
Modifying the collection (such as adding and deleting elements) during traversal may causeConcurrentModificationException

Performance considerations
Priority is given to scenarios that are sensitive to large data volume or performanceforCycling (slightly excellent performance).

5. Common scenario examples

1️⃣ Iterate over and process elements

val numbers = listOf(10, 20, 30)
 { 
    val squared = it * it
    println(squared)
}

2️⃣ Traverse the file contents

File("").readLines().forEach { line ->
    println(())
}

3️⃣ Verify data

data class User(val name: String, val age: Int)
val users = listOf(User("Alice", 30), User("Bob", 17))
 { user ->
    require( >= 18) { "${} Minor!" }
}

6. Summary

Core role: Iterate through the collection elements and perform operations.
Applicable scenarios: Simple traversal without returning value operation.
Alternatives: Used when complex control flow is requiredforLoop; use when you need to return a new setmap/filter

passforEachIt can make the code more concise, but it needs to be paid attention to its limitations.

This is all about this article about kotlin function forEach. For more related kotlin function forEach, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!