Kotlin Flattening
Flattening turns a collection of collections into one flat collection. flatMap builds a small collection for each value and flattens all of them in one step.
Flattening a list of lists
flatten removes one level of nesting. The three inner lists become one list.
fun main() {
val groups = listOf(listOf(1, 2), listOf(3), listOf(4, 5))
println(groups.flatten())
}Flattening word groups
The inner lists hold words here. The result holds every word in order.
fun main() {
val groups = listOf(listOf("a", "b"), listOf("c"))
println(groups.flatten())
println(groups.flatten().size)
}Expanding each value with flatMap
Each word maps to a pair of the word and its length. flatMap flattens those pairs into one list.
fun main() {
val words = listOf("ant", "beetle")
println(words.flatMap { listOf(it, it.length) })
}Turning strings into characters
toList turns one string into its characters. flatMap joins the characters of all the strings.
fun main() {
val words = listOf("ab", "cd")
println(words.flatMap { it.toList() })
}Example
fun main() {
val shelves = listOf(listOf("ant", "ape"), listOf("bat"))
println(shelves.flatten())
val words = listOf("hi", "go")
println(words.flatMap { it.toList() })
println(words.flatMap { listOf(it, it.length) })
}Key points
- flatten joins the inner lists of a list of lists into one list.
- The values keep their original order after flattening.
- flatMap first maps each value to a collection.
- flatMap then flattens those collections into one result.
- A string becomes a list of its characters with toList.
In this example, flatten joins the two shelf lists into one list of three words. The first flatMap splits each word into its characters. The second flatMap pairs each word with its length.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
What does listOf(listOf(1), listOf(2, 3)).flatten() return?