Map: Looking Up by Key
At the end of the week the coach asks, "How far did Chen run?" Searching a list of name and distance pairs one by one is slow and clumsy. A Map files each value under a key, so the answer is one lookup away.
The rule
Keys are unique; ask with
getorgetOrElsewhen a key might be missing.
val weekKm = Map("Asha" -> 26.7, "Ben" -> 18.0, "Chen" -> 31.4)
weekKm("Chen") // 31.4
weekKm.get("Chen") // Some(31.4)
weekKm.get("Dara") // None
weekKm.getOrElse("Dara", 0.0) // 0.0
weekKm("Dara") // throws NoSuchElementException"Asha" -> 26.7makes a pair, the same as("Asha", 26.7). A Map is built from pairs of key and value.- Each key appears once. Adding a pair whose key already exists replaces that key's value.
m(key)assumes the key is there and throws if it is not.m.get(key)returns anOption:Some(value)when found,Nonewhen not.getOrElsesupplies a default for the missing case.
The default Map is immutable, so "changes" return a new map:
val withDara = weekKm + ("Dara" -> 12.0) // four entries
val fixed = weekKm.updated("Ben", 21.0) // Ben's value replaced
val noChen = weekKm - "Chen" // two entriesOther handy parts: weekKm.contains("Asha") is true, weekKm.keys gives the names, and weekKm.values the distances. A for can take each pair apart as it goes:
for (name, km) <- weekKm do println(s"$name: $km km")Like a Set, a Map does not promise any particular order.
The shortcut
Before any lookup, ask "can this key be missing?" If the key came from the map itself, for example from weekKm.keys, then m(key) is fine. If it came from a person, a form or another list, use getOrElse with a sensible default, or get when the absence itself matters.
Where does the key come from?
"Dara" was typed by the coach, and Dara has not logged a run yet.
Drills
Answer fast — trust the rule.
What is weekKm("Chen")?
What is weekKm.get("Dara")?
What is (weekKm + ("Asha" -> 30.0)).size?
What does weekKm("Dara") do?
What is "Asha" -> 26.7?
Remember
- A Map files values under unique keys, and
->builds a key and value pair. - Ask "can this key be missing?" If so, use
getOrElseorget. - Trap:
m(key)throws on a missing key, and adding an existing key replaces its value.
