August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to get all of the keys or values from a 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.keySetres0: scala.collection.immutable.Set[String] = Set(AK, AL, AR) scala>states.keysres1: Iterable[String] = Set(AK, AL, AR) scala>states.keysIteratorres2: 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.valuesres0: Iterable[String] = MapLike(Alaska, Alabama, Arkansas) scala>states.valuesIteratorres1: 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.
Read now
Unlock full access