Kotlin

associate and associateBy

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`associateBy` builds a `Map<K, T>` keyed by a derived value. `associateWith` keys by the items themselves with derived values. `associate` lets you build both key and value from each item.
Kotlin
Raw
data class User(val id: Int, val name: String, val email: String)

fun main() {
    val users = listOf(
        User(1, "Alice", "a@x.com"),
        User(2, "Bob",   "b@x.com"),
        User(3, "Cara",  "c@x.com"),
    )

    // associateBy — Map<K, T>: pick the key, value is the item itself
    val byId: Map<Int, User> = users.associateBy { it.id }
    println(byId[2])                                  // User(id=2, name=Bob, ...)

    // associate — Map<K, V>: build both from each item
    val emailByName: Map<String, String> = users.associate { it.name to it.email }
    println(emailByName)

    // associateWith — keys are the items themselves, value is derived
    val nameLengths: Map<String, Int> = listOf("Alice", "Bob").associateWith { it.length }
    println(nameLengths)                              // {Alice=5, Bob=3}
}
Tags

Save your own code snippets

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