0
0
Kotlinprogramming~5 mins

Iterating collections with forEach in Kotlin

Choose your learning style9 modes available
Introduction
You use forEach to go through each item in a list or collection easily, doing something with each item without writing a loop yourself.
When you want to print all items in a list one by one.
When you need to apply the same action to every element, like increasing numbers or changing text.
When you want to check or process each item without changing the list itself.
When you want cleaner and simpler code instead of writing a full loop.
When you want to run a small piece of code for each item quickly.
Syntax
Kotlin
collection.forEach { item ->
    // action with item
}
The 'collection' can be a list, set, or any group of items.
Inside the curly braces, 'item' represents each element as you go through the collection.
Examples
Prints each number in the list one by one.
Kotlin
val numbers = listOf(1, 2, 3)
numbers.forEach { number ->
    println(number)
}
Uses the default name 'it' for each item to print a message.
Kotlin
val fruits = listOf("apple", "banana", "cherry")
fruits.forEach {
    println("I like $it")
}
Uses forEachIndexed to get both the position and the item.
Kotlin
val names = listOf("Anna", "Bob", "Cara")
names.forEachIndexed { index, name ->
    println("Person $index is $name")
}
Sample Program
This program prints each color in the list with the word 'Color:' before it.
Kotlin
fun main() {
    val colors = listOf("red", "green", "blue")
    colors.forEach { color ->
        println("Color: $color")
    }
}
OutputSuccess
Important Notes
forEach is simple and readable but does not change the original collection.
If you want to create a new list with changed items, use map instead.
You cannot use break or continue inside forEach like in a normal loop.
Summary
forEach helps you do something with every item in a collection easily.
It uses a small block of code that runs for each element.
Great for simple actions like printing or checking items.