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.
Practice
(1/5)
1. What does the flatMap function do when applied to a nested list in Kotlin?
easy
A. It filters elements based on a condition.
B. It sorts the nested lists in ascending order.
C. It transforms each element and flattens the result into a single list.
D. It converts the list into a set to remove duplicates.
Solution
Step 1: Understand flatMap behavior
flatMap applies a transformation to each element and then flattens the nested results into one list.
Step 2: Compare with other functions
Unlike sorting, filtering, or converting to a set, flatMap combines mapping and flattening in one step.
Final Answer:
It transforms each element and flattens the result into a single list. -> Option C
Quick Check:
flatMap = transform + flatten [OK]
Hint: Remember: flatMap = map + flatten in one step [OK]
Common Mistakes:
Confusing flatMap with filter or sort
Thinking flatMap removes duplicates
Assuming flatMap only maps without flattening
2. Which of the following is the correct syntax to use flatMap on a list of lists named nestedList in Kotlin?
easy
A. nestedList.flatMap { it }
B. nestedList.flatMap()
C. nestedList.flatMap -> it
D. nestedList.flatMap { it.flatten() }
Solution
Step 1: Identify correct lambda syntax
The flatMap function requires a lambda to transform each element. { it } returns each inner list as is.
Step 2: Check other options
nestedList.flatMap() misses lambda, C uses wrong arrow syntax, D uses flatten() incorrectly on flat inner lists.
Final Answer:
nestedList.flatMap { it } -> Option A
Quick Check:
flatMap needs a lambda like { it } [OK]
Hint: flatMap always needs a lambda block { } [OK]
Common Mistakes:
Omitting the lambda block
Using arrow (->) instead of curly braces
Using flatten() instead of identity mapping
3. What is the output of the following Kotlin code?
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it.map { it * 2 } }
println(result)
medium
A. [[2, 4], [6, 8]]
B. [1, 2, 3, 4]
C. [2, 4, [6, 8]]
D. [2, 4, 6, 8]
Solution
Step 1: Understand inner map transformation
Each inner list element is multiplied by 2, so listOf(1,2) becomes listOf(2,4), and listOf(3,4) becomes listOf(6,8).
Step 2: Apply flatMap flattening
flatMap flattens the transformed lists into one list: [2, 4, 6, 8].
Final Answer:
[2, 4, 6, 8] -> Option D
Quick Check:
flatMap + map doubles and flattens [OK]
Hint: flatMap flattens after map transformation [OK]
Common Mistakes:
Expecting nested lists instead of flat list
Ignoring the inner map multiplication
Confusing output with original nested list
4. Identify the error in this Kotlin code snippet using flatMap:
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it * 2 }
println(result)
medium
A. flatMap requires a filter inside the lambda.
B. Cannot multiply a list by an integer directly.
C. The variable 'nested' is not defined.
D. flatMap should be replaced with map.
Solution
Step 1: Analyze the lambda expression
The lambda tries to multiply it (a list) by 2, which is invalid in Kotlin.
Step 2: Understand flatMap requirements
flatMap expects a lambda returning an iterable, but it * 2 causes a type error.
Final Answer:
Cannot multiply a list by an integer directly. -> Option B
Quick Check:
List * Int is invalid in Kotlin [OK]
Hint: Check types inside lambda; lists can't be multiplied by numbers [OK]
Common Mistakes:
Assuming list * number works like in some other languages
Thinking flatMap needs a filter
Confusing map and flatMap usage
5. Given a list of students where each student has a list of grades, how can you use flatMap to get a single list of all grades above 70?
data class Student(val name: String, val grades: List<Int>)
val students = listOf(
Student("Alice", listOf(80, 65)),
Student("Bob", listOf(90, 72)),
Student("Carol", listOf(60, 85))
)
// Fill in the blank:
val passingGrades = students.flatMap { ________ }
println(passingGrades)
hard
A. it.grades.filter { grade -> grade > 70 }
B. it.grades.map { grade -> grade > 70 }
C. it.grades.filter { grade -> grade < 70 }
D. it.grades
Solution
Step 1: Filter grades above 70 for each student
Inside the lambda, use it.grades.filter { grade -> grade > 70 } to keep only passing grades.
Step 2: Use flatMap to flatten all filtered grades
flatMap combines all filtered lists into one flat list of passing grades.