This article explores different ways to convert a list to a map in Kotlin.

1. Using associate() function

The standard way to convert a list to a map is with the associate() function. It returns a map containing key-value pairs provided by the transform function applied to the given list elements.

In the following example, we’ll construct a Map from List of Color objects. The Color class contains the name and hex field. They represent the color name and its corresponding HTML color code, respectively.

Download Code

2. Using associateBy() function

Another good solution is to use the associateBy() function that takes two lambdas for generating the key and the value.

Download Code

3. Using map() function

Another plausible way is to use the map() function to generate a list of Key-Value Pairs and then call the toMap() function to transform it into a map.

Download Code

4. Custom Routine

You can write your custom logic for transforming a list into a map. Here’s what the code would look like:

Download Code

That’s all about converting a list to a map in Kotlin.