Complete the code to flatten the list of lists using flatMap.
val nestedList = listOf(listOf(1, 2), listOf(3, 4)) val flatList = nestedList.[1] { it } println(flatList)
The flatMap function flattens the nested lists into a single list by applying the given lambda.
Complete the code to extract all words from a list of sentences using flatMap.
val sentences = listOf("hello world", "kotlin is fun") val words = sentences.[1] { it.split(" ") } println(words)
flatMap applies the lambda to each sentence and flattens the resulting lists of words into one list.
Fix the error in the code to flatten a list of nullable lists using flatMap.
val listOfNullableLists: List<List<Int>?> = listOf(listOf(1, 2), null, listOf(3)) val flatList = listOfNullableLists.[1] { it ?: emptyList() } println(flatList)
flatMap is used with a lambda that replaces null with an empty list to safely flatten the collection.
Fill both blanks to create a flat list of all characters from a list of words.
val words = listOf("cat", "dog") val chars = words.[1] { it.[2]() } println(chars)
flatMap applies the lambda to each word, and toCharArray() converts each word to a list of characters, which are then flattened into one list.
Fill all three blanks to create a map of words to their lengths, but only for words longer than 3 characters.
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)
map transforms each word, the condition checks if length is greater than 3, and to creates a pair for the map.