Kotlin Map - forEach() Function



The Kotlin Map forEach() function is used to loops across the map, and it is easier to perform the given operation or action on each value of key in map.

There are the following use cases of the forEach() function:

  • Iterate through a Collection: It simplifies iteration by applying a given lambda function to each element.
  • Perform Operation: We can perform custom operation on each key, like logging, transformation, and validation.
  • Improve Code Readability: As compared to traditional for loop. ForEach result is cleaner and more concise.

Syntax

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

inline fun <T> Map<T>.forEach(operation: (T) -> Unit)

Parameters

This function accepts a lambda function as a parameter that specifies the operation to be performed on each element.

Return value

This function does not return any values.

Example 1: Iterating Over a Map

Let's see a basic example of the forEach() function, which display the elements of map.

fun main() {
   val studentScores = mapOf(
      "Aman" to 85,
      "Akanksha" to 92,
      "Vivek" to 80,
      "Akash" to 88
   )
   // Traverse the map using forEach
   studentScores.forEach { (name, score) ->
      println("Student: $name, Score: $score")
   }
}

Output

Following is the output −

Student: Aman, Score: 85
Student: Akanksha, Score: 92
Student: Vivek, Score: 80
Student: Akash, Score: 88

Example 2: Modify External Variable

The following example uses forEach() function to iterate through the map values to calculate the sum −

fun main(args: Array<String>) {
   val numbers = mapOf(1 to 5, 2 to 10, 3 to 15, 4 to 20)
   var sum = 0

   // Iterate through the map values to calculate the sum
   numbers.forEach { (_, value) -> sum += value }

   println("Sum of numbers: $sum")
}

Output

Following is the output −

Sum of numbers: 50

Example 3: Applying a Discount to Product Prices

This is another example of forEach() function to perform action on a Map. Let's apply a discount to product price stored in a map and display the updated prices −

fun main(args: Array<String>) {
   val products = mapOf(
      "Laptop" to 1500.0,
      "Smartphone" to 800.0,
      "Tablet" to 600.0,
      "Headphones" to 200.0
   )
   // 10% discount
   val discount = 10.0

   // Traverse the map and apply the discount to each price
   products.forEach { (product, price) ->
      val discountedPrice = price - (price * discount / 100)
      println("$product: Original Price = \$${price}, Discounted Price = \$${"%.2f".format(discountedPrice)}")
   }
}

Output

Following is the output −

Laptop: Original Price = $1500.0, Discounted Price = $1350.00
Smartphone: Original Price = $800.0, Discounted Price = $720.00
Tablet: Original Price = $600.0, Discounted Price = $540.00
Headphones: Original Price = $200.0, Discounted Price = $180.00
kotlin_maps.htm
Advertisements