11.18. Getting the Keys or Values from a Map
Problem
You want to get all of the keys or values from a 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.
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.