Kotlin Map - map() Function



The Kotlin Map map() function works seamlessly as a collection, just like it does with a list and set. It transforms its entries (key-value pairs) into another. It applies the specified Lambda function to the entries of the original map and returns them in the newly created list.

The behaviour is slightly different from working with lists or sets, because the function operates on the entries of the map, represented by the Map.Entry class.

There are following use cases of the map() function −

  • Transformed value of key: It can manipulate value such as increasing the score and modifying the value of the value. Manipulate keys such as adding prefixes and converting formats.
  • Extracting Specific Data: It can extract a list of keys or values.
  • Create Derived Maps: It generates the new map by transforming the key, values, or both.

Syntax

Following is the syntax of Kotlin set map() function −

originalMap.map { (key, value) -> transformFunction(key, value) }

Parameters

This function accepts lambda function as a parameter to define a transformation logic.

Return value

This function returns a list containing the results of applying the given transform function.

Example 1: Transforming Value

Let's see a basic example of the map() function, which transform the values of a map into a new list −

fun main(args: Array<String>) {
   val scores = mapOf("Aman" to 90, "Kaushal" to 85, "Dipak" to 95)
   val gradeMessages = scores.map { (name, score) -> "$name scored $score" }
   
   // results a list
   println(gradeMessages)
}

Output

Following is the output −

[Aman scored 90, Kaushal scored 85, Dipak scored 95]

Example 2: Creating a Transformed map

In the following example, we can transform the map into another map by applying the toMap() after the map() function −

fun main(args: Array<String>) {
   val scores = mapOf("Aman" to 90, "Kaushal" to 85, "Dipak" to 95)
   val adjustedScores = scores.map { (name, score) -> name to (score + 5) }.toMap()
   println(adjustedScores)
}

Output

Following is the output −

{Aman=95, Kaushal=90, Dipak=100}

Example 3: Extracting Key and Values

This is another example of the map() function to create a list of keys or values only −

fun main(args: Array<String>) {
   val scores = mapOf("Aman" to 90, "Kaushal" to 85, "Dipak" to 95)
   
   // Extract keys
   val names = scores.map { it.key }
   println(names)
   
   // Extract values
   val grades = scores.map { it.value }
   println(grades)
}

Output

Following is the output −

[Aman, Kaushal, Dipak]
[90, 85, 95]
kotlin_maps.htm
Advertisements