Kotlin

flatMap and Flattening

admin by @admin ADMIN
4d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`flatMap` maps each item to a collection, then concatenates. Use it when "for each X, produce N Y's, collect all Y's". `flatten()` is the no-mapping version.
Kotlin
Raw
data class User(val name: String, val tags: List<String>)

fun main() {
    val users = listOf(
        User("Alice", listOf("admin", "editor")),
        User("Bob",   listOf("editor", "viewer")),
        User("Cara",  listOf("admin")),
    )

    // All tags across all users (with duplicates)
    val allTags: List<String> = users.flatMap { it.tags }
    println(allTags)                                   // [admin, editor, editor, viewer, admin]

    // Distinct tags
    println(allTags.distinct())                        // [admin, editor, viewer]

    // flatten — when you already have a List<List<T>>
    val nested = listOf(listOf(1, 2), listOf(3, 4, 5), listOf(6))
    println(nested.flatten())                          // [1, 2, 3, 4, 5, 6]

    // String chars from a list of words
    val chars = listOf("hi", "bye").flatMap { it.toList() }
    println(chars)                                     // [h, i, b, y, e]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.