Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List to Map in Kotlin?

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.

like image 840
LordScone Avatar asked Oct 17 '22 08:10

LordScone


People also ask

What does .map do in Kotlin?

Returns a list containing the results of applying the given transform function to each element in the original array. Returns a list containing the results of applying the given transform function to each element in the original collection.

How do I convert a list to map in Scala?

To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.


1 Answers

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()
like image 417
voddan Avatar answered Oct 18 '22 21:10

voddan