0
0
Kotlinprogramming~20 mins

FlatMap for nested collections in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
FlatMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1, 2, 3, 4]
B[4, 8]
C[[2, 4], [6, 8]]
D[2, 4, 6, 8]
Attempts:
2 left
💡 Hint
Remember that flatMap flattens one level after mapping.
Predict Output
intermediate
1: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)
A3
B2
C1
D0
Attempts:
2 left
💡 Hint
flatMap flattens one level of nested lists.
🔧 Debug
advanced
2: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)
ANullPointerException at runtime
BNo error, output: [2, 4, 6, 8]
CType mismatch: 'it' is List<Int>, cannot multiply by Int
DIndexOutOfBoundsException
Attempts:
2 left
💡 Hint
Check the operation inside the lambda for flatMap.
Predict Output
advanced
2: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)
A[1, 3, 5]
B[2, 4]
C[2, 3, 4, 5]
D[1, 2, 3, 4, 5]
Attempts:
2 left
💡 Hint
Filter keeps only even numbers before flattening.
🧠 Conceptual
expert
2: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?
AflatMap applies a transformation and flattens the result into a single list, avoiding nested lists.
BflatMap only works with lists of integers, while map works with any type.
CflatMap is faster because it uses parallel processing automatically.
DflatMap changes the original list, while map creates a new list.
Attempts:
2 left
💡 Hint
Think about the shape of the output collections.