0
0
Kotlinprogramming~5 mins

Iterating collections with forEach in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the forEach function do in Kotlin collections?
It runs a given block of code on each item in the collection, one by one.
Click to reveal answer
beginner
How do you write a forEach loop to print each element in a list called numbers?
numbers.forEach { number -> println(number) }
Click to reveal answer
intermediate
Can you modify elements inside a forEach loop in Kotlin?
No, forEach is used for actions like printing or logging. To change elements, use map or other transformation functions.
Click to reveal answer
intermediate
What is the difference between a for loop and forEach in Kotlin?
for is a language construct that can be used with any iterable, while forEach is a function that takes a lambda and runs it on each element.
Click to reveal answer
beginner
Write a forEach example that prints each string in a list with its length.
val words = listOf("apple", "banana", "cherry") words.forEach { word -> println("$word has ${word.length} letters") }
Click to reveal answer
What type of argument does forEach take in Kotlin?
AA string value
BAn integer index
CA lambda function that takes each element
DA Boolean condition
Which of these is a correct way to use forEach on a list items?
AforEach(items) { println(it) }
Bitems.forEach -> println(it)
Citems.forEach(println(it))
Ditems.forEach { println(it) }
Can forEach be used to change the elements of a mutable list directly?
ANo, it is for performing actions only
BYes, it modifies elements automatically
COnly if the list is immutable
DOnly with a special keyword
What will this code print?
listOf(1, 2, 3).forEach { println(it * 2) }
A2 4 6
B1 2 3
CError
D6 4 2
Which Kotlin collection function is best for transforming elements instead of just iterating?
AforEach
Bmap
Cfilter
Dreduce
Explain how to use forEach to print all elements in a Kotlin list.
Think about how you tell the list to do something with each item.
You got /3 concepts.
    Describe the difference between forEach and a for loop in Kotlin.
    Consider how each handles looping and control flow.
    You got /4 concepts.