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}
}
Create a free account and build your private vault. Share publicly whenever you want.