
上QQ阅读APP看书,第一时间看更新
Map
Map is defined as trait Map[K, +V] extends Iterable[(K, V)] with MapOps[K, V, Map, Map[K, V]] with Equals which makes it an Iterable over pairs of key, K, and value, V. It also defines a notion of equality among maps. The class hierarchy for Map is represented on the following diagram:
There are three different MapOps, one general for both mutable and immutable, and one specific for each of these forms.
MapOps extends IterableOps with the following specific operations:
- Element retrieval: get, getOrElse, apply, applyOrElse, default, contains, and isDefinedAt. These methods allow us to retrieve a value or check whether a value is present by a given key, optionally returning a default value or throwing an exception if the key can't be found.
- Subcollection retrieval: keySet, keys, values, keysIterator, and valuesIterator allow us to get a keys or values in different forms.
- Mapping: map, flatMap, and collect are transforming and optionally filtering the pairs of keys and values.
- Addition: concat returns a new collection with elements of both maps combined.
immutable.MapOps adds the following methods on top of MapOps:
- Element removal: remove, removeAll, -- removes one or all given elements from the map returning new map.
- Element updates: updated and + update an element with the given key returning new map.
- Mapping: transform applies a given function to all elements, producing a new map with the returned results as values.
mutable.MapOps has a different set of methods as compared to the mutable one:
- Element addition: put adds a new value or updates existing one.
- Element update: updated, +, and getOrElseUpdate updates a value in place.
- Element removal: remove and clear remove one or all elements of the map.
- Filtering: filterInPlace retains only mappings that satisfy the predicate.
- Mapping: mapValuesInPlace applies a transformation to the values of the map, storing returned results as values.
The general Map definition has quite a few specialized subtypes, as shown in the preceding diagram. We will take a quick look at them now.