CodeBlanks Logo Icon CodeBlanks

flatMap and flatten

Learn flattening with flatMap and flatten.

flatMap and flatten

flatMap transforms each element into a list and concatenates them. flatten flattens a nested list by one level.

Example: listOf("ab", "cd").flatMap { it.toList() } returns [a, b, c, d]. listOf(listOf(1, 2), listOf(3, 4)).flatten() gives [1, 2, 3, 4]. flatMap = map + flatten. This pattern is used to flatten nested structures.

Flatten a nested list

flatten reduces a nested list by one level. When no transform is needed, flatten is more readable than flatMap.

Example: listOf(listOf(1, 2), listOf(3, 4), listOf(5)).flatten(). This returns [1, 2, 3, 4, 5]. flatten only reduces one level; deeper structures require multiple calls. This pattern is used to expand grouped data into a single list.

Practice Split words into letters with flatMap

In main assign the result of listOf("apple", "pear").flatMap { it.toList() } to a variable and print it with println.

Starter code

Main.kt
// in main split two words into letters with flatMap
// print the result with println

Sample solution

Main.kt
fun main() {
    val chars = listOf("apple", "pear").flatMap { it.toList() }
    println(chars)
}

Expected output

[a, p, p, l, e, p, e, a, r]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the flatMap call

Question
val chars = listOf("ab", "cd").____ { it.toList() }
Answer
val chars = listOf("ab", "cd").flatMap { it.toList() }

Explanation: flatMap turns each element into a list and concatenates.

2 Match the flatMap/flatten parts

Term Meaning
flatMap { } Transform and merge
flatten() One-level reduce
it.toList() Convert to list
[1, 2, 3, 4] Result

3 What does listOf(listOf(1, 2), listOf(3, 4)).flatten() return?

  • [[1, 2], [3, 4]]
  • [1, 2, 3, 4] Correct answer
  • [1, 2]
  • [3, 4]

Explanation: flatten reduces a nested list by one level.

All lessons in Advanced