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 = Arizona
However, 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: FOO
One 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 state
You can also use the get
method, which returns an Option
:
scala> val az = states.get("AZ")
az: Option[String] = Some(Arizona) ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.