w3resource

Scala Map: Creating and adding key-value pairs

Scala Map Exercise-1 with Solution

Write a Scala program to create an empty map and add key-value pairs to it.

Sample Solution:

Scala Code:

object AddKeyValuePairsToMapExample {
  def main(args: Array[String]): Unit = {
    // Create an empty map
    var color = Map.empty[String, Int]

    // Add key-value pairs to the map
    color = color + ("Red" -> 1)
    color = color + ("Green" -> 2)
    color = color + ("Blue" -> 3)
    color = color + ("Orange" -> 4)

    // Print the map
    println("Map: " + color)
  }
}

Sample Output:

Map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4)

Explanation:

In the above exercise,

  • First, we create an empty map "color" using the Map.empty method. We declare it as a var (mutable).
  • To add key-value pairs to the map, we use the + operator and assign the result back to the "color" variable. This way, the updated map is stored in the same variable.
  • Finally, we print the "color" using println.

Scala Code Editor :

Previous: Scala Map Exercises Home.
Next: Check if a map is empty.

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://w3resource.com/scala-exercises/map/scala-map-exercise-1.php