How to convert List to Map in Kotlin?

LordScone picture LordScone · Oct 4, 2015 · Viewed 63.6k times · Source

For example I have a list of strings like:

val list = listOf("a", "b", "c", "d")

and I want to convert it to a map, where the strings are the keys.

I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.

Answer

voddan picture voddan · Oct 4, 2015

You have two choices:

The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:

val map = friends.associateBy({it.facebookId}, {it.points})

The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:

val map = friends.map { it.facebookId to it.points }.toMap()