Challenge - 5 Problems
FlatMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of flatMap on nested lists
What is the output of this Kotlin code using
flatMap on nested lists?Kotlin
val nested = listOf(listOf(1, 2), listOf(3, 4)) val result = nested.flatMap { it.map { it * 2 } } println(result)
Attempts:
2 left
💡 Hint
Remember that flatMap flattens one level after mapping.
✗ Incorrect
The inner map doubles each number, producing [[2,4],[6,8]]. flatMap then flattens this to a single list [2,4,6,8].
❓ Predict Output
intermediate1:30remaining
Result size after flatMap
Given this Kotlin code, how many elements does
result contain?Kotlin
val nested = listOf(listOf("a", "b"), listOf("c")) val result = nested.flatMap { it } println(result.size)
Attempts:
2 left
💡 Hint
flatMap flattens one level of nested lists.
✗ Incorrect
The nested list has 2 elements in the first list and 1 in the second, total 3 elements after flattening.
🔧 Debug
advanced2:00remaining
Identify the error in flatMap usage
What error does this Kotlin code produce?
Kotlin
val nested = listOf(listOf(1, 2), listOf(3, 4)) val result = nested.flatMap { it * 2 } println(result)
Attempts:
2 left
💡 Hint
Check the operation inside the lambda for flatMap.
✗ Incorrect
The lambda tries to multiply a list by 2, which is invalid in Kotlin, causing a type mismatch error.
❓ Predict Output
advanced2:00remaining
Output of flatMap with filtering
What is the output of this Kotlin code using flatMap with a filter?
Kotlin
val nested = listOf(listOf(1, 2, 3), listOf(4, 5)) val result = nested.flatMap { it.filter { it % 2 == 0 } } println(result)
Attempts:
2 left
💡 Hint
Filter keeps only even numbers before flattening.
✗ Incorrect
The filter keeps only even numbers: 2 from first list, 4 from second. flatMap flattens to [2, 4].
🧠 Conceptual
expert2:30remaining
Why use flatMap instead of map for nested collections?
Which statement best explains why
flatMap is preferred over map when working with nested collections in Kotlin?Attempts:
2 left
💡 Hint
Think about the shape of the output collections.
✗ Incorrect
flatMap combines mapping and flattening in one step, producing a single-level list instead of nested lists.