Kotlin List - toMap() Function



The Kotlin List toMap() function converts a list of key-value pairs or pair objects into a map. Where each element of the list is treated as a key-value pair. A map stores key-value pairs, and the key must be unique.

This function is commonly useful when we represent data in pairs and want to work with it as a map.

Syntax

Following is the syntax of the Kotlin list toMap() function −

fun <K, V> list<out Pair<K, V>>.toMap(): Map<K, V>

Parameters

This function does not accepts any parameters.

Return value

This function returns a map that contains the key-value pairs from list.

Example 1: Converting a List of Pairs into a Map

Let's see a basic example of the toMap() function, which return a map containing key-value pairs −

fun main(args: Array<String>) {
   val pairs = listOf("a" to 1, "b" to 2, "c" to 3)
   val map = pairs.toMap()
   println("Map: $map")
}

Output

Following is the output −

Map: {a=1, b=2, c=3}

Example 2: Handling Duplicate Key

In the following example, we use the toMap() function. If the list contains duplicate keys, the last value for the key will overwrite earlier ones −

fun main(args: Array<String>) {
   val pairs = listOf("a" to 1, "b" to 2, "a" to 3)
   val map = pairs.toMap()
   println("Map: $map")
}

Output

Following is the output −

Map: {a=3, b=2}

Example 3: Map From a List Object

In this example, suppose we have a list of Person objects, and we want to create a map where the key is the person's Id, and value is their name −

data class Person(val id: Int, val name: String)

fun main() {
   val people = listOf(
      Person(1, "Aman"),
      Person(2, "Vivek"),
      Person(3, "Dipak"),
      Person(2, "David")
   )

   // Convert the list of people to a map with ID 
   // as the key and name as the value
   val peopleMap = people.map { it.id to it.name }.toMap()

   println("Original list: $people")
   println("Generated map: $peopleMap")
}

Output

Following is the output −

Original list: [Person(id=1, name=Aman), Person(id=2, name=Vivek), Person(id=3, name=Dipak), Person(id=2, name=David)]
Generated map: {1=Aman, 2=David, 3=Dipak}
kotlin_lists.htm
Advertisements