Scala Map: Retrieving values by key
Scala Map Exercise-4 with Solution
Write a Scala program to create a map and retrieve the value associated with a given key.
Sample Solution:
Scala Code:
object RetrieveValueFromMapExample {
def main(args: Array[String]): Unit = {
// Create a map
val color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
// Print the map
println("Map: " + color_map)
// Retrieve the value associated with a key
val color_key = "Blue"
val value = color_map.getOrElse(color_key, "Key not found")
// Print the result
println(s"The value associated with key '$color_key' is: $value")
}
}
Sample Output:
Map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4) The value associated with key 'Blue' is: 3
Explanation:
In the above exercise -
- First, we create a map "color_map" using the Map constructor and provide key-value pairs.
- To retrieve the value associated with a given key, we use the "getOrElse()" method on the map. We pass the key we want to retrieve and provide a default value if the key is not found on the map.
- In this example, we retrieve the value associated with the key "Blue". If the key is found, the corresponding value is assigned to the value variable. Otherwise, the default value of "Key not found" is assigned.
- Finally, we use println to print the result, including the key and the retrieved value.
Scala Code Editor :
Previous: Find the size of a map.
Next: Update values by key.
What is the difficulty level of this exercise?
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-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics