11.16. Accessing Map Values
Problem
You want to access individual values stored in a map. You may have tried this and run into an exception when a key didn’t exist, and want to see how to avoid that exception.
Solution
Given a sample map:
scala> val states = Map("AL" -> "Alabama", "AK" -> "Alaska", "AZ" -> "Arizona")
states: scala.collection.immutable.Map[String,String] =
Map(AL -> Alabama, AK -> Alaska, AZ -> Arizona)Access the value associated with a key in the same way you access an element in an array:
scala> val az = states("AZ")
az: String = ArizonaHowever, be careful, because if the map doesn’t contain the
requested key, a java.util.NoSuchElementException exception is
thrown:
scala> val s = states("FOO")
java.util.NoSuchElementException: key not found: FOOOne way to avoid this problem is to create the map with the
withDefaultValue method. As the name
implies, this creates a default value that will be returned by the map
whenever a key isn’t found:
scala>val states = Map("AL" -> "Alabama").withDefaultValue("Not found")states: scala.collection.immutable.Map[String,String] = Map(AL -> Alabama) scala>states("foo")res0: String = Not found
Another approach is to use the getOrElse method when attempting to find a
value. It returns the default value you specify if the key isn’t
found:
scala> val s = states.getOrElse("FOO", "No such state")
s: String = No such stateYou can also use the get
method, which returns an Option:
scala> val az = states.get("AZ") az: Option[String] = Some(Arizona) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access