Kotlin List to Map: associate, associateBy, associateWith & groupBy

Kotlin course · Collections · Lesson 31 of 51

Updated:

To convert a List to a Map in Kotlin, use one of the standard library functions: associateBy (list items become the values), associateWith (list items become the keys), associate (you build both key and value), toMap (for a list of pairs) or groupBy (when several items share a key). Here’s when to use each, with examples.

Quick comparison

FunctionResultUse when
associateBy { key }Map<K, T>Index objects by a field, e.g. users by id
associateWith { value }Map<T, V>The list items are the keys, e.g. word → length
associate { key to value }Map<K, V>You need a custom key and value
toMap()Map<K, V>You already have a List<Pair<K, V>>
groupBy { key }Map<K, List<T>>Several items share the same key and you want to keep all of them
keys.zip(values).toMap()Map<K, V>Keys and values are in two separate lists

All examples below use this list:

data class User(val id: Int, val name: String, val city: String)

val users = listOf(
    User(1, "Asha", "Delhi"),
    User(2, "Ravi", "Mumbai"),
    User(3, "Meera", "Delhi")
)

1. associateBy – list items become the values

val usersById: Map<Int, User> = users.associateBy { it.id }
// {1=User(1, Asha, Delhi), 2=User(2, Ravi, Mumbai), 3=User(3, Meera, Delhi)}

println(usersById[2]?.name) // Ravi

You can also transform the value at the same time:

val namesById: Map<Int, String> = users.associateBy({ it.id }, { it.name })
// {1=Asha, 2=Ravi, 3=Meera}

2. associateWith – list items become the keys

val words = listOf("kotlin", "map", "list")
val lengths: Map<String, Int> = words.associateWith { it.length }
// {kotlin=6, map=3, list=4}

3. associate – build key and value yourself

val nameToCity: Map<String, String> = users.associate { it.name to it.city }
// {Asha=Delhi, Ravi=Mumbai, Meera=Delhi}

4. toMap – from a list of pairs

val pairs = listOf("a" to 1, "b" to 2, "c" to 3)
val map: Map<String, Int> = pairs.toMap()
// {a=1, b=2, c=3}

5. groupBy – keep all items with the same key

val usersByCity: Map<String, List<User>> = users.groupBy { it.city }
// {Delhi=[User(1, Asha, Delhi), User(3, Meera, Delhi)], Mumbai=[User(2, Ravi, Mumbai)]}

val namesByCity: Map<String, List<String>> = users.groupBy({ it.city }, { it.name })
// {Delhi=[Asha, Meera], Mumbai=[Ravi]}

6. Two lists: zip then toMap

val keys = listOf("x", "y", "z")
val values = listOf(10, 20, 30)
val map = keys.zip(values).toMap()
// {x=10, y=20, z=30}

zip stops at the shorter list, so extra keys or values are dropped.

What happens with duplicate keys?

With associate, associateBy and toMap, if two items produce the same key, the last one wins and earlier ones are silently dropped:

val byCity = users.associateBy { it.city }
// {Delhi=User(3, Meera, Delhi), Mumbai=User(2, Ravi, Mumbai)} – Asha is lost

If duplicates are possible and you need every item, use groupBy instead. To keep the first item, reverse the list first or use distinctBy { it.city } before converting.

Order and mutability

  • The returned map keeps the order of the original list (it’s a LinkedHashMap under the hood).
  • The result is a read-only Map. Call .toMutableMap() if you need to add or remove entries, or use associateTo(mutableMapOf()) { … } to fill an existing map.

Map back to a List

val map = mapOf(1 to "Asha", 2 to "Ravi")

map.toList()                                 // [(1, Asha), (2, Ravi)]
map.keys.toList()                            // [1, 2]
map.values.toList()                          // [Asha, Ravi]
map.map { (id, name) -> "$id: $name" }       // [1: Asha, 2: Ravi]

FAQ

What is the difference between associate and associateBy?

associateBy only asks for the key and uses the item itself as the value. associate lets you return both key and value as a Pair.

How do I convert a list to a map with the index as key?

Use list.withIndex().associate { it.index to it.value }, or list.mapIndexed { i, v -> i to v }.toMap().

Which is fastest?

They are all a single pass over the list. Choose the one that best describes what you want – the code is easier to read.

More Kotlin guides

WhatsApp us📞 Call now