Bird
Raised Fist0
Kotlinprogramming~20 mins

Iterating collections with forEach in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
forEach Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using forEach?

Consider the following Kotlin code snippet:

val numbers = listOf(1, 2, 3)
numbers.forEach { print(it * 2) }

What will be printed when this code runs?

Kotlin
val numbers = listOf(1, 2, 3)
numbers.forEach { print(it * 2) }
A246
B123
C6
DError: forEach cannot be used on List
Attempts:
2 left
💡 Hint

Remember that forEach applies the given action to each element in the list.

🧠 Conceptual
intermediate
2:00remaining
Which statement about Kotlin's forEach is true?

Choose the correct statement about the forEach function in Kotlin collections.

A<code>forEach</code> can be used to modify the elements of a mutable list directly.
B<code>forEach</code> is a terminal operation that applies a given action to each element.
C<code>forEach</code> returns a new list with transformed elements.
D<code>forEach</code> can only be used with arrays, not lists.
Attempts:
2 left
💡 Hint

Think about what forEach does with the elements and its return type.

🔧 Debug
advanced
2:00remaining
What error does this Kotlin code raise?

Examine the code below:

val items = listOf("a", "b", "c")
items.forEach { it = it.uppercase() }

What error will this code produce?

Kotlin
val items = listOf("a", "b", "c")
items.forEach { it = it.uppercase() }
ATypeError: Cannot assign to 'it' because it is a val
BSyntaxError: Missing lambda arrow
CNullPointerException
DNo error, prints uppercase letters
Attempts:
2 left
💡 Hint

Consider whether the lambda parameter it can be reassigned.

❓ Predict Output
advanced
2:00remaining
What is the output of this Kotlin code using forEachIndexed?

Consider this Kotlin code:

val list = listOf("x", "y", "z")
list.forEachIndexed { index, value -> print("$index$value") }

What will be printed?

Kotlin
val list = listOf("x", "y", "z")
list.forEachIndexed { index, value -> print("$index$value") }
A012
Bxyz
CError: forEachIndexed not found
D0x1y2z
Attempts:
2 left
💡 Hint

Remember forEachIndexed provides both index and element.

📝 Syntax
expert
2:00remaining
Which option causes a compilation error in Kotlin forEach usage?

Which of the following Kotlin code snippets will cause a compilation error?

A
val nums = listOf(1, 2, 3)
nums.forEach { println(it + 1) }
B
val nums = listOf(1, 2, 3)
nums.forEach { val it = it + 1; println(it) }
C
val nums = listOf(1, 2, 3)
nums.forEach(it -&gt; println(it))
D
val nums = listOf(1, 2, 3)
nums.forEach { number -&gt; println(number) }
Attempts:
2 left
💡 Hint

Check the lambda syntax in Kotlin carefully.

Practice

(1/5)
1. What does the forEach function do when used on a list in Kotlin?
easy
A. It runs a block of code for each item in the list.
B. It creates a new list with modified items.
C. It removes items from the list.
D. It sorts the list in ascending order.

Solution

  1. Step 1: Understand the purpose of forEach

    The forEach function is designed to execute a given block of code on every element in a collection.
  2. Step 2: Compare options with forEach behavior

    Only It runs a block of code for each item in the list. correctly describes this behavior. Options B, C, and D describe other functions like map, remove, and sort.
  3. Final Answer:

    It runs a block of code for each item in the list. -> Option A
  4. Quick Check:

    forEach = run code on each item [OK]
Hint: forEach runs code on every element, not changing the list [OK]
Common Mistakes:
  • Confusing forEach with map that creates new lists
  • Thinking forEach modifies the list itself
  • Assuming forEach sorts or filters the list
2. Which of the following is the correct syntax to print each element of a list numbers using forEach in Kotlin?
easy
A. numbers.forEach -> println(it)
B. forEach(numbers) { println(it) }
C. numbers.forEach { println(it) }
D. numbers.forEach(println(it))

Solution

  1. Step 1: Recall the correct forEach syntax

    In Kotlin, forEach is called on the collection with a lambda block: collection.forEach { item -> ... }. The shorthand uses it for the current item.
  2. Step 2: Check each option's syntax

    numbers.forEach { println(it) } matches the correct syntax. forEach(numbers) { println(it) } wrongly uses forEach as a function with the list as argument. numbers.forEach(println(it)) incorrectly calls println inside forEach parentheses. numbers.forEach -> println(it) uses an invalid arrow syntax.
  3. Final Answer:

    numbers.forEach { println(it) } -> Option C
  4. Quick Check:

    Correct forEach syntax = numbers.forEach { println(it) } [OK]
Hint: Use collection.forEach { println(it) } to print items [OK]
Common Mistakes:
  • Calling forEach as a standalone function
  • Passing println(it) directly inside forEach parentheses
  • Using arrow (->) outside lambda block
3. What will be the output of the following Kotlin code?
val fruits = listOf("apple", "banana", "cherry")
fruits.forEach { println(it.length) }
medium
A. 5 6 6
B. 5 6 6
C. apple banana cherry
D. 3 6 6

Solution

  1. Step 1: Understand the code behavior

    The list fruits contains three strings: "apple", "banana", and "cherry". The forEach prints the length of each string.
  2. Step 2: Calculate lengths and output format

    "apple" has length 5, "banana" has length 6, "cherry" has length 6. Each println prints on a new line, so output is: 5 6 6
  3. Final Answer:

    5 6 6 -> Option B
  4. Quick Check:

    Print lengths with println = lines of 5,6,6 [OK]
Hint: println prints each item on a new line [OK]
Common Mistakes:
  • Assuming output is on one line separated by spaces
  • Confusing string length with number of vowels
  • Printing the strings instead of their lengths
4. Identify the error in this Kotlin code snippet:
val nums = listOf(1, 2, 3)
nums.forEach(i -> println(i))
medium
A. Calling println inside forEach is not allowed
B. Missing parentheses after forEach
C. Using val instead of var for list
D. Using arrow (->) instead of curly braces for lambda

Solution

  1. Step 1: Check lambda syntax in Kotlin

    Kotlin uses curly braces {} for lambdas, not arrow notation like -> outside braces. The arrow is used inside the lambda to separate parameters from body.
  2. Step 2: Identify the incorrect usage

    The code uses i -> println(i) directly after forEach without braces, which is invalid syntax. Correct form is nums.forEach { i -> println(i) }.
  3. Final Answer:

    Using arrow (->) instead of curly braces for lambda -> Option D
  4. Quick Check:

    Lambda needs braces {} around arrow -> [OK]
Hint: Use { param -> code } for lambdas, not (param -> code) [OK]
Common Mistakes:
  • Using arrow notation without braces
  • Confusing Kotlin lambda syntax with other languages
  • Thinking val vs var affects forEach usage
5. Given a list of integers nums, how can you use forEach to print only the even numbers?
hard
A. nums.forEach { if (it % 2 == 0) println(it) }
B. nums.forEach { println(it % 2 == 0) }
C. nums.forEach { if (it / 2 == 0) println(it) }
D. nums.forEach { println(it) if (it % 2 == 0) }

Solution

  1. Step 1: Understand the condition for even numbers

    An even number has zero remainder when divided by 2, so it % 2 == 0 checks if a number is even.
  2. Step 2: Use if inside forEach to print only even numbers

    nums.forEach { if (it % 2 == 0) println(it) } correctly uses an if statement inside the lambda to print only when the condition is true. Other options either print booleans or have incorrect syntax.
  3. Final Answer:

    nums.forEach { if (it % 2 == 0) println(it) } -> Option A
  4. Quick Check:

    Use if inside forEach to filter printing [OK]
Hint: Use if (it % 2 == 0) inside forEach to print evens [OK]
Common Mistakes:
  • Printing boolean results instead of numbers
  • Using division instead of modulo for even check
  • Placing if after println causing syntax error
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard