0
0
Kotlinprogramming~10 mins

FlatMap for nested collections in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to flatten the list of lists using flatMap.

Kotlin
val nestedList = listOf(listOf(1, 2), listOf(3, 4))
val flatList = nestedList.[1] { it }
println(flatList)
Drag options to blanks, or click blank then click option'
Amap
Bfilter
CflatMap
DforEach
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of flatMap results in a list of lists, not a flat list.
2fill in blank
medium

Complete the code to extract all words from a list of sentences using flatMap.

Kotlin
val sentences = listOf("hello world", "kotlin is fun")
val words = sentences.[1] { it.split(" ") }
println(words)
Drag options to blanks, or click blank then click option'
AflatMap
Bmap
Cfilter
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using map will create a list of lists of words instead of a flat list.
3fill in blank
hard

Fix the error in the code to flatten a list of nullable lists using flatMap.

Kotlin
val listOfNullableLists: List<List<Int>?> = listOf(listOf(1, 2), null, listOf(3))
val flatList = listOfNullableLists.[1] { it ?: emptyList() }
println(flatList)
Drag options to blanks, or click blank then click option'
Aflatten
BfilterNotNull
Cmap
DflatMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using map will keep the nested structure.
Using flatten directly on nullable lists causes errors.
4fill in blank
hard

Fill both blanks to create a flat list of all characters from a list of words.

Kotlin
val words = listOf("cat", "dog")
val chars = words.[1] { it.[2]() }
println(chars)
Drag options to blanks, or click blank then click option'
AflatMap
Bmap
CtoList
DtoCharArray
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of flatMap results in a list of arrays, not a flat list.
Using toList() returns a list of strings, not characters.
5fill in blank
hard

Fill all three blanks to create a map of words to their lengths, but only for words longer than 3 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val result = words.[1] { word ->
    if (word.length [2] 3) mapOf(word [3] word.length) else emptyMap<String, Int>()
}
println(result)
Drag options to blanks, or click blank then click option'
AflatMap
B>
Cto
Dmap
Attempts:
3 left
💡 Hint
Common Mistakes
Using flatMap instead of map changes the structure.
Using '<' instead of '>' changes the filter condition.
Using '=' instead of 'to' causes syntax errors.