How to Use flatMap on List in Kotlin: Syntax and Examples
In Kotlin, you can use the
flatMap function on a list to transform each element into a list and then flatten all those lists into a single list. It combines mapping and flattening in one step, making it easy to work with nested collections.Syntax
The flatMap function takes a lambda that returns a list for each element. It applies this lambda to every element, then merges all resulting lists into one.
list.flatMap { element -> listOfTransformedElements }- The lambda returns a list for each element.
- The final result is a single flattened list.
kotlin
val result = list.flatMap { element -> listOf(element, element * 2) }Example
This example shows how to use flatMap to double each number and keep the original, then flatten the results into one list.
kotlin
fun main() {
val numbers = listOf(1, 2, 3)
val doubledAndOriginal = numbers.flatMap { number -> listOf(number, number * 2) }
println(doubledAndOriginal)
}Output
[1, 2, 2, 4, 3, 6]
Common Pitfalls
A common mistake is using map instead of flatMap when you want a single flattened list. map returns a list of lists, not a flat list.
Also, ensure the lambda returns a list, not a single element.
kotlin
fun main() {
val numbers = listOf(1, 2, 3)
// Wrong: map returns List<List<Int>>
val mapped = numbers.map { number -> listOf(number, number * 2) }
println(mapped) // Output: [[1, 2], [2, 4], [3, 6]]
// Correct: flatMap returns List<Int>
val flatMapped = numbers.flatMap { number -> listOf(number, number * 2) }
println(flatMapped) // Output: [1, 2, 2, 4, 3, 6]
}Output
[[1, 2], [2, 4], [3, 6]]
[1, 2, 2, 4, 3, 6]
Quick Reference
- flatMap: transforms and flattens a list of lists into a single list.
- Use when each element maps to multiple elements.
- Returns a flat list, unlike
mapwhich returns nested lists.
Key Takeaways
Use
flatMap to transform and flatten nested lists in one step.The lambda inside
flatMap must return a list for each element.Avoid using
map when you want a single flat list; it returns nested lists.The result of
flatMap is a single list containing all elements from the inner lists.FlatMap is useful for working with nested or grouped data in Kotlin collections.