0
0
Kotlinprogramming~5 mins

FlatMap for nested collections in Kotlin

Choose your learning style9 modes available
Introduction

FlatMap helps you turn a list of lists into a single list by combining all inner lists. It makes working with nested collections easier.

You have a list of lists and want one flat list with all items.
You want to process nested data like a list of orders, each with multiple products.
You need to simplify nested loops by flattening collections.
You want to transform and flatten data in one step.
You want to collect all elements from nested collections into one list.
Syntax
Kotlin
val flatList = nestedList.flatMap { innerList ->
    innerList.map { item ->
        // transform item if needed
        item
    }
}

flatMap takes each inner list and combines all results into one list.

You can transform items inside the map before flattening.

Examples
This example flattens a list of lists of numbers into one list.
Kotlin
val nested = listOf(listOf(1, 2), listOf(3, 4))
val flat = nested.flatMap { it }
println(flat)
This example converts all strings to uppercase while flattening.
Kotlin
val nested = listOf(listOf("a", "b"), listOf("c"))
val flat = nested.flatMap { inner -> inner.map { it.uppercase() } }
println(flat)
Sample Program

This program shows how to flatten nested lists of numbers and strings. It also transforms strings to have the first letter capitalized.

Kotlin
fun main() {
    val nestedNumbers = listOf(listOf(10, 20), listOf(30, 40), listOf(50))
    val flatNumbers = nestedNumbers.flatMap { it }
    println("Flat list: $flatNumbers")

    val nestedWords = listOf(listOf("cat", "dog"), listOf("bird"))
    val flatWords = nestedWords.flatMap { inner -> inner.map { it.replaceFirstChar { c -> c.uppercase() } } }
    println("Capitalized flat list: $flatWords")
}
OutputSuccess
Important Notes

Remember, flatMap combines mapping and flattening in one step.

If you only want to flatten without changing items, you can just use flatMap { it }.

Use map if you want to keep the nested structure.

Summary

flatMap turns nested lists into one flat list.

It lets you transform and flatten data in one go.

Great for simplifying nested collections and loops.