Convert a List to Map – Kotlin

List to Map Conversion in Kotlin

In this tutorial, we will explore various methods for converting a List to a Map in Kotlin, illustrated with practical examples.

1. Using associateBy

Kotlin offers a straightforward way to convert a list to a Map using associateBy. This method requires a keySelector and a valueTransformer. In the following example, the list element serves as the key, and its length as the value.

Output:

The resulting map is immutable, and if there are duplicate keys, the last value is used. This behavior is different from Java lambdas, where you must explicitly define duplicate handling. If not specified, Java throws an exception, which can lead to issues in production code.

2. Using toMap

Kotlin collections offer a toMap() method, which is a simple way to convert a collection to a map. However, you must first call the map() method to transform each list element into a Pair.

Output:

The code above can be condensed into a single line:

The returned map is also immutable. We will discuss mutable map conversion later.

3. Using associate

The associate method is another way to convert a List to a Map. You can pass a transformer function that converts list elements into Pairs.

Output:

These conversion methods preserve the original list order. The returned map is a LinkedHashMap, which maintains the ordering.

4. Using associateTo

The previous examples produced immutable Maps. If you need a mutable Map, associateTo enables this by accepting a mutable Map and adding the collection items based on your transformer.

Output:

5. Using groupByTo

In cases where you want to keep all values for a key, you can use groupByTo, which maps each key to a list of values.

Output:

You can use groupBy if you don’t need a mutable Map.

Output:

Summary

In this tutorial, we examined various methods for converting a List to a Map in Kotlin. These techniques should prove helpful in learning Kotlin basics. Feel free to share your suggestions in the comments.

References

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.