Kotlin How to Convert List to Map with Examples
associateBy { keySelector } to create a map with keys from list elements or associate { key to value } to define both keys and values explicitly.Examples
How to Think About It
associateBy if keys come from each element and values are the elements themselves. Use associate if you want to create both keys and values from each element.Algorithm
Code
fun main() {
val fruits = listOf("apple", "banana", "cherry")
val mapByFirstLetter = fruits.associateBy { it.first() }
println(mapByFirstLetter)
val mapCustom = fruits.associate { it to it.length }
println(mapCustom)
}Dry Run
Let's trace converting list ["apple", "banana", "cherry"] to map by first letter
Start with list
["apple", "banana", "cherry"]
Extract key for each element
Keys: 'a' from "apple", 'b' from "banana", 'c' from "cherry"
Create map entries
{'a' to "apple", 'b' to "banana", 'c' to "cherry"}
| Element | Key | Value |
|---|---|---|
| apple | a | apple |
| banana | b | banana |
| cherry | c | cherry |
Why This Works
Step 1: Using associateBy
associateBy creates a map where keys come from a function applied to each element, and values are the elements themselves.
Step 2: Using associate
associate lets you define both keys and values by returning pairs from each element.
Step 3: Resulting map
The output is a map where each key points to its corresponding value as defined by your functions.
Alternative Approaches
fun main() {
val fruits = listOf("apple", "banana", "cherry")
val map = mutableMapOf<Char, String>()
for (fruit in fruits) {
map[fruit.first()] = fruit
}
println(map)
}fun main() {
val fruits = listOf("apple", "banana", "cherry")
val pairs = fruits.map { it.first() to it }
val map = pairs.toMap()
println(map)
}Complexity: O(n) time, O(n) space
Time Complexity
The conversion loops through the list once, so time grows linearly with list size.
Space Complexity
A new map is created with one entry per list element, so space grows linearly.
Which Approach is Fastest?
associateBy and associate are optimized and concise; manual loops may be slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| associateBy | O(n) | O(n) | Simple key extraction |
| associate | O(n) | O(n) | Custom keys and values |
| for loop with mutableMap | O(n) | O(n) | Complex logic during conversion |
| map + toMap | O(n) | O(n) | Clear pair creation before map |
associateBy for simple key extraction and associate when you need custom keys and values.