Scala Map: Remove key-value pairs
Write a Scala program to create a map and remove a key-value pair from it.
Sample Solution:
Scala Code:
object RemoveKeyValuePairFromMapExample {
def main(args: Array[String]): Unit = {
// Create a map
var color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
// Print the original map
println("Original map: " + color_map)
// Remove a key-value pair from the map
val keyToRemove = "Blue"
val updatedMap = color_map.removed(keyToRemove)
// Print the updated map
println("Updated map: " + updatedMap)
}
}
Sample Output:
Original map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4) Updated map: Map(Red -> 1, Green -> 2, Orange -> 4)
Scala Code Editor :
Previous: Update values by key.
Next: Key-value pair traversal.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics