List — flatMap() / flatten()
Kotlin's flatMap() transforms each element into a list and flattens the results into a single list. flatten() flattens a nested list (List<List<T>>) by one level.
Syntax
// flatMap — Transforms each element and flattens the results.
val words = listOf("hello", "world")
val chars = words.flatMap { it.toList() }
// ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
// flatten — Flattens a nested list by one level.
val nested = listOf(listOf(1, 2), listOf(3, 4), listOf(5))
val flat = nested.flatten() // [1, 2, 3, 4, 5]
// Equivalent to map + flatten
val same = words.map { it.toList() }.flatten()
Method List
| Method | Description |
|---|---|
| list.flatMap { v -> list } | Transforms each element into a list and concatenates them into a single list. |
| list.flatMapIndexed { i, v -> list } | Performs flatMap using both the index and the element. |
| nestedList.flatten() | Flattens a List<List<T>> into a List<T> (one level only). |
| sequence.flatMap { } | Performs flatMap lazily on a sequence. |
Sample Code
data class Department(val name: String, val members: List<String>)
fun main() {
// flatten — Flattens a nested list by one level.
val matrix = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
println("flatten: ${matrix.flatten()}")
println()
// flatMap — Converts per-department member lists into a single list of all members.
val departments = listOf(
Department("Engineering", listOf("Alice", "Bob", "Carol")),
Department("Sales", listOf("Dave", "Eve")),
Department("HR", listOf("Frank"))
)
// Build a list of all members.
val allMembers = departments.flatMap { it.members }
println("All members: $allMembers")
// Build a list with department names attached.
val withDept = departments.flatMap { dept ->
dept.members.map { "${dept.name}: $it" }
}
withDept.forEach { println(it) }
println()
// Count character frequencies using flatMap.
val words = listOf("kotlin", "java", "swift")
val allChars = words.flatMap { it.toList() }
println("Total characters: ${allChars.size}")
val freq = allChars.groupingBy { it }.eachCount().entries.sortedByDescending { it.value }
println("Top characters: ${freq.take(3).map { "${it.key}:${it.value}" }}")
println()
// Use flatMapIndexed to include index information.
val lines = listOf("AAA", "BB", "CCCC")
val indexed = lines.flatMapIndexed { lineIdx, line ->
line.mapIndexed { charIdx, ch -> "[$lineIdx,$charIdx]$ch" }
}
println("With indices: $indexed")
// Handle nullable elements by filtering them out before flattening.
val groups: List<List<Int>?> = listOf(listOf(1, 2), null, listOf(3, 4))
val flatSafe = groups.filterNotNull().flatten()
println("After removing nulls: $flatSafe")
}
Notes
flatMap() is commonly used for "one-to-many transform and merge" patterns. It is well-suited for operations similar to SQL JOINs or collecting all leaf nodes from a tree structure.
flatten() only flattens one level at a time. For more deeply nested lists, you need to call flatten() multiple times or use a recursive approach.
For zip/unzip combinations, see List — zip() / unzip(). For grouping, see List — groupBy() / partition().
If you find any errors or copyright issues, please contact us.