Scala - Map
Create Map
immutable
val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
mutable
val scores = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
empty
val scores = new scala.collection.mutable.HashMap[String, Int]
Accessing map values
val bobsScore = scores("Bob")
val bobsScore = if (scores.contains("Bob")) scores("Bob") else 0
// if the map contains the key "Bob", return the value; otherwise, return 0.
val bobsScore = scores.getOrElse("Bob", 0)
Updating map values
// Updates the existing value for the key "Bob". (assuming scores is mutable)
scores("Bob") = 10
// Adds a new key/value pair to scores. (assuming scores is mutable)
scores("Fred") = 7
// += : multiple associations
scores += ("Bob" -> 10, "Fred" -> 7)
// delete key/values
scores -= "Alice"
// you cannot update immutable map.
// but you can obtain a new map with Updates
val newScores = scores + ("Bob" -> 10, "Fred" -> 7)
iterating over map
for ((k, v) <- map) process k and v
// key
scores.keySet // Set
// values
scores.values