Scala Maps in Depth
Working with maps in depth means looking values up, updating entries, and transforming a whole map. Each step returns a value you can check, never the whole map printed out.
Get shows present and missing keys
The first lookup finds a value, so it prints Some of that value. The second lookup finds nothing, so it prints None.
@main def main(): Unit =
val m = Map("a" -> 1, "b" -> 2)
println(m.get("a"))
println(m.get("z"))Sorted keys and summed values are safe to print
Sorting the keys gives a fixed order, and summing the values gives one number. Neither print prints the map itself.
@main def main(): Unit =
val m = Map("b" -> 2, "a" -> 1, "c" -> 3)
println(m.keys.toList.sorted)
println(m.values.sum)Updated returns a new map
The original map still holds 2 for the key b. The updated map holds 9 for the same key, which proves the original did not change.
@main def main(): Unit =
val m = Map("a" -> 1, "b" -> 2)
val m2 = m.updated("b", 9)
println(m.getOrElse("b", 0))
println(m2.getOrElse("b", 0))Example
@main def main(): Unit =
val words = List("scala", "java", "scala", "kotlin", "scala")
val counts = words.foldLeft(Map.empty[String, Int])((m, w) => m.updated(w, m.getOrElse(w, 0) + 1))
println(counts.keys.toList.sorted)
println(counts.getOrElse("scala", 0))
println(counts.getOrElse("java", 0))Key points
- Get: get returns Some of the value for a present key, and None for a missing key.
- GetOrElse: getOrElse returns the value for a key, or a fallback when the key is missing.
- Updated: updated returns a new map with one entry changed or added.
- Keys: keys gives the keys, and sorting them gives a fixed order to print.
- Values: values gives the values, so you can sum them or check them one by one.
In this example, the fold walks the words and updates a count for each word, starting from an empty map. The sorted keys show the three distinct words, and the two lookups show that scala appeared three times and java appeared once.
Note
updated leaves the original map unchanged, because maps return new maps instead of changing in place.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
A map holds "a" -> 1. What does m.updated("a", 5) do to the original map?