w3resource

Scala map iteration: Key-value pair traversal

Scala Map Exercise-7 with Solution

Write a Scala program to create a map and iterate over its key-value pairs.

Sample Solution:

Scala Code:

object IterateOverMapExample {
  def main(args: Array[String]): Unit = {
    // Create a map
    var color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)

    // Iterate over the map's key-value pairs
    for ((key, value) <- color_map) {
      println(s"Key: $key, Value: $value")
    }
  }
}

Sample Output:

Key: Red, Value: 1
Key: Green, Value: 2
Key: Blue, Value: 3
Key: Orange, Value: 4

Explanation:

In the above exercise, we create a map "color_map" using the Map constructor and provide key-value pairs.

To iterate over the map's key-value pairs, we use a for loop with a pattern match. The pattern (key, value) matches each key-value pair in the map. Inside the loop, we can access the key and value variables to print or perform other operations.

Each key-value pair is printed using println, where $key and $value are placeholders for the actual key and value.

Scala Code Editor :

Previous: Remove key-value pairs.
Next: Verify key existence in a map.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.