How to get the keys or values from a Scala Map

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shortest recipes, Recipe 11.19, “How to Get the Keys or Values from a Scala Map”

Problem

You want to get all of the keys or values from a Scala Map.

Solution

To get the keys, use keySet to get the keys as a Set, keys to get an Iterable, or keysIterator to get the keys as an iterator:

scala> val states = Map("AK" -> "Alaska", "AL" -> "Alabama", "AR" -> "Arkansas")
states: scala.collection.immutable.Map[String,String] = Map(AK -> Alaska, AL -> Alabama, AR -> Arkansas)

scala> states.keySet
res0: scala.collection.immutable.Set[String] = Set(AK, AL, AR)

scala> states.keys
res1: Iterable[String] = Set(AK, AL, AR)

scala> states.keysIterator
res2: Iterator[String] = non-empty iterator

To get the values from a map, use the values method to get the values as an Iterable, or valuesIterator to get them as an Iterator:

scala> states.values
res0: Iterable[String] = MapLike(Alaska, Alabama, Arkansas)

scala> states.valuesIterator
res1: Iterator[String] = non-empty iterator

As shown in these examples, keysIterator and valuesIterator return an iterator from the map data. I tend to prefer these methods because they don’t create a new collection; they just provide an iterator to walk over the existing elements.