How to convert a List to a Map in Kotlin?

AndroidMobile DevelopmentApps/ApplicationsKotlin

In this article, we will see how we can convert a List to a Map using various options provided by the Kotlin Library.

Example: Using associate()

The most standard way of converting a list into a map is by using the associate() function. This function takes a list of items as an argument and it returns a map containing key-value pairs. In the following example, we will see how it works.

Example

data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of values in it.
   val myMap: Map<String, String> = mySubjectList.associate {
      Pair(it.priority, it.name)
   }

   println(myMap)
}

Output

Once we run the above piece of code, it will generate the following output which is a map and we get the output in a key-value format.

{1=Java, 2=Kotlin, 3=C}

Example: Using associateBy()

AssociateBy() is another function that can be used in order to transform a list into a Map. In the following example, we will see how we can implement the same.

Example

data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of the values in it
   val myMap: Map<String, String> = mySubjectList.associateBy(
      {it.priority}, {it.name}
   )

   println(myMap)
}

Output

It will generate the following output which is a map and we get the output in a key-value format.

{1=Java, 2=Kotlin, 3=C}

Example: Using toMap()

Kotlin library provides another function to convert a list of items into a Map. Kotlin Map class contains a function called toMap() which returns a new map containing all the key-value pairs from a given collection. Let's see how it works.

Example

data class mySubjectList(var name: String, var priority: String)

fun main() {
   val mySubjectList: List<mySubjectList> = listOf(
      mySubjectList("Java", "1"),
      mySubjectList("Kotlin", "2"),
      mySubjectList("C", "3")
   )

   // Creating a map and adding my own list of the values in it .
   val myMap: Map<String, String> = mySubjectList.map{
      it.priority to it.name
   }.toMap()

   println(myMap)
}

Output

Once we run the above piece of code, it will generate the following output which is a map and we get the output in a key-value format.

{1=Java, 2=Kotlin, 3=C}
raja
Updated on 27-Oct-2021 11:31:57

Advertisements