Kotlin

groupBy and partition

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`groupBy` returns a `Map<Key, List<T>>` keyed by what the lambda returns. `partition` is a special-case `groupBy` for booleans — returns `(matching, nonMatching)` Pair.
Kotlin
Raw
data class User(val name: String, val team: String, val active: Boolean)

fun main() {
    val users = listOf(
        User("Alice", "A", true),
        User("Bob",   "B", false),
        User("Cara",  "A", true),
        User("Dave",  "B", true),
    )

    // groupBy — bucket by any key
    val byTeam: Map<String, List<User>> = users.groupBy { it.team }
    println(byTeam.mapValues { (_, v) -> v.size })    // {A=2, B=2}

    // groupingBy + eachCount — count per group in one pass
    val countByTeam = users.groupingBy { it.team }.eachCount()
    println(countByTeam)                              // {A=2, B=2}

    // partition — split by a boolean predicate
    val (active, inactive) = users.partition { it.active }
    println("active: ${active.size}, inactive: ${inactive.size}")

    // associateBy — like groupBy but assumes UNIQUE keys → Map<K, T>
    val byName = users.associateBy { it.name }
    println(byName["Alice"])
}
Tags

Save your own code snippets

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