w3resource

Scala Map: Update values by key

Scala Map Exercise-5 with Solution

Write a Scala program to create a map and update the value associated with a given key.

Sample Solution:

Scala Code:

object UpdateValueInMapExample {
  def main(args: Array[String]): Unit = {
    // Create a mutable map
    var color_map = collection.mutable.Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
    
    // Print the original map
    println("Original map: " + color_map)

    // Update the value associated with a key
    val key = "Green"
    val newValue = 7
    color_map(key) = newValue

    // Print the updated map
    println("Updated map: " + color_map)
  }
}

Sample Output:

Original map: HashMap(Red -> 1, Orange -> 4, Blue -> 3, Green -> 2)
Updated map: HashMap(Red -> 1, Orange -> 4, Blue -> 3, Green -> 7)

Explanation:

In the above exercise -

  • First, we create a mutable map "color_map" using the mutable.Map constructor provides key-value pairs. Note that we use var instead of val to make the map mutable.
  • To update the value associated with a given key, we use the assignment operator =. In this example, we update the value associated with the key "Green" to 7 by assigning newValue to map(key).
  • Finally, we print the original and updated maps using println.

Scala Code Editor :

Previous: Retrieving values by key.
Next: Remove key-value pairs.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/map/scala-map-exercise-5.php