This article explores different ways to convert a List<Pair<K,V>> to a Map<K,V> in Kotlin.

1. Using associate() function

The associate() function returns a map containing key-value pairs provided by the transform function applied to elements of the given map. It can be used as follows to convert a List<Pair<K,V>> to a Map<K,V> in Kotlin:

Download Code

 
Alternatively, we can use the following shorthand form:

Download Code

2. Using associateBy() function

The associateBy() function returns a map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given map. It can be used as follows to convert a List<Pair<K,V>> to a Map<K,V> in Kotlin:

Download Code

 
The above code is short for the following:

Download Code

3. Using map() function

Another option is to use the map() library function to extract keys and values from the List of Pairs and uses the toMap() function to build a map:

Download Code

4. Using Loop

Finally, we can write custom logic for converting a list of pairs into a map. This can be implemented as follows in Kotlin. Note that the code throws IllegalStateException on encountering a duplicate key. The code can be easily modified to handle duplicate keys.

Download Code

That’s all about converting a List<Pair<K,V>> to a Map<K,V> in Kotlin.