Convert a List to Map – Kotlin

In this tutorial we would learn different ways to convert a List to Map in Kotlin. We would be describing the list to Map conversion in Kotlin with different examples.

1.  Using associateBy

Kotlin provides a simple way to convert a list to Map. Using associateBy, a list can be converted to Map, by using a keySelector and a valueTransformer. In the below simple example, key is the  list element and value is the length of each element.

Output is :

The map returned is an immutable Map. If any of two pairs would have the same key the last one gets added to the map. That is an important difference to the Java lambdas where you have explicitly define the behavior in case of duplicates. This sometimes leads to ugly situations in code. If you don’t define the behavior in Java, it throws an exception. And I have seen so many such exceptions in production code. These hardly get detected while testing. And most often the fix is to accept the last value. And Kotlin does it by default. Thanks Kotlin.

2.  With toMap

Collections in Kotlin provide a method toMap(). It is one of the simplest way to convert a collection to map. But we have to call map() method to transform each of the list element to a Pair.

Output is:

I have tried to have more lines of code above, so that we can all see all the return types of different intermediate operations. we can write the above code in oneliner.

The map returned is an immutable map. We will look below, how to have a MutableMap in conversion.

3. associate

associate method can be used to convert List to Map as below. You can pass transformer function that converts the list elements to Pair.

output :

All these conversion methods keep the original order of the list. The type of map returned is a LinkedHashMap which explains how the ordering is preserved.

4.  associateTo

In all the above methods what we achieved was to get an immutable Map. If we need a Map that we would need to modify after the conversion then associateByTo provides the possibility to do so. We can pass a mutable Map to the method and it adds the collection items based on our transformator to the provided Map.

output

5.  groupByTo

As we discussed in the first example that in case of duplicate key, the value is replaced with the last Value. There may be some cases where all the values have to kept in the Map and hence each key may be mapped to a List of values. This is what groupByTo achieves.

output :

groupBy can also be used if you don’t need a mutable Map.

Summary

We looked at various ways of converting list to Map. These have been quite useful for me and I hope these help you learning the basics of Kotlin. Any suggestions are welcome in comments.

References :

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html

Leave a Reply