How to access Map values in Scala

This is an excerpt from the Scala Cookbook (#ad) (partially modified for the internet). This is one of the shortest recipes, Recipe 11.17, “How to Access Map Values in Scala”

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)

scala> val az = states.get("FOO")
az: Option[String] = None

To loop over the values in a map, see the next recipe.

See Also

  • Recipe 11.21, “Testing for the Existence of a Key or Value in a Map”
  • Recipe 20.6, “Using the Option/Some/None Pattern” shows how to work with Option, Some, and None values