0
0
Kotlinprogramming~10 mins

Iterating collections with forEach in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iterating collections with forEach
Start with collection
Call forEach on collection
Take first element
Execute lambda with element
Take next element?
NoEnd
Back to Execute lambda
The forEach function takes each element from a collection one by one and runs the given code block (lambda) on it until all elements are processed.
Execution Sample
Kotlin
val numbers = listOf(1, 2, 3)
numbers.forEach { n ->
    println(n * 2)
}
This code goes through each number in the list and prints double its value.
Execution Table
StepCurrent Element (n)ActionOutput
11Execute lambda: println(1 * 2)2
22Execute lambda: println(2 * 2)4
33Execute lambda: println(3 * 2)6
4-No more elements, forEach ends-
💡 All elements processed, forEach stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
n-123-
Key Moments - 2 Insights
Why does the variable 'n' change each step inside forEach?
Because forEach takes each element from the collection one by one and assigns it to 'n' before running the lambda, as shown in execution_table rows 1 to 3.
Does forEach return a new collection or change the original?
No, forEach only runs the code on each element and returns Unit (nothing). It does not create or change collections, as seen by no changes in variable_tracker except 'n' during iteration.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when 'n' is 2?
A4
B2
C6
D8
💡 Hint
Check row 2 in the execution_table where n=2 and output is printed
At which step does forEach stop running the lambda?
AStep 3
BStep 4
CStep 1
DStep 2
💡 Hint
Look at the exit note and step 4 in execution_table where no more elements remain
If the list had one more element 4, how many times would the lambda run?
A3 times
B5 times
C4 times
D1 time
💡 Hint
forEach runs once per element, so check variable_tracker for count of elements
Concept Snapshot
forEach iterates over each element in a collection.
Syntax: collection.forEach { element -> /* code */ }
Runs the code block for every element.
Does not return a new collection.
Useful for actions like printing or updating UI.
Full Transcript
This example shows how to use forEach in Kotlin to go through each item in a list. The code takes each number and prints double its value. The flow starts by calling forEach on the list, then for each element, it runs the lambda code. The variable 'n' holds the current element and changes each step. The execution table shows each step with the current element and output. The process stops when all elements are done. forEach does not create or change collections, it just runs code on each item.