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”


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


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.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.