与 Collection 部分相比,Java 集合框架的 Map 部分相对简单,其大致结构如下图所示:
map.svg

Map 接口

Map 接口是 Map 部分的根接口,它规定了 map 结构内部的 key-value 对称为 entry,一个 map 中的 key 不能有重复,一个 key 仅能对应一个 value。

对于该接口来说,最重要的内容是其定义了如下 3 个 view 方法:

  1. Set<K> keySet();
  2. Collection<V> values();
  3. Set<Map.Entry<K, V>> entrySet();

除此之外, Map 接口定义的几个 default method 也很实用:

  1. default V getOrDefault(Object key, V defaultValue) {...}
  2. default V putIfAbsent(K key, V value) {...}
  3. default void forEach(BiConsumer<? super K, ? super V> action) {...}
  4. default boolean replace(K key, V oldValue, V newValue) {...}
  5. default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {...}
  6. default boolean remove(Object key, Object value) {...}
  7. default V replace(K key, V value) {...}
  8. default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {...}
  9. default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {...}
  10. default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {...}
  11. default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {...}

SortedMap 接口

顾名思义, SortedMapMap 的基础上增加了有序性,这种有序性是按 key 来排序的,有两种排序机制:

  • 所有的 key 都实现 Comparable 接口;
  • 提供一个 Comparator

SortedMap 的有序性是基于 compareTo()compare() 方法实现的,这自然而然就涉及到 consistent with equals() 的问题,你可以参考前文的介绍,这里不再赘述。

因为有序性的实现,使得我们可以取出 submap,为此 SortedMap 接口提供了如下几个方法:

  1. SortedMap<K,V> subMap(K fromKey, K toKey);
  2. SortedMap<K,V> headMap(K toKey);
  3. SortedMap<K,V> tailMap(K fromKey);

SortedMap 提供了如下 2 个方法也值得注意:

  1. K firstKey();
  2. K lastKey();

NavigableMap 接口

NavigableMapSortedMap 的基础上新增了以下几个特性:

  • navigation methods
  • a reverse order view of the map

其中 navigation methods 用于返回最匹配的 key,有如下方法:

  1. // < - less than
  2. Map.Entry<K,V> lowerEntry(K key);
  3. K lowerKey(K key);
  4. // <= - less than or equal
  5. Map.Entry<K,V> floorEntry(K key);
  6. K floorKey(K key);
  7. // >= - greater than or equal
  8. Map.Entry<K,V> ceilingEntry(K key);
  9. K ceilingKey(K key);
  10. // > = greater than
  11. Map.Entry<K,V> higherEntry(K key);
  12. K higherKey(K key);

此外, NavigableMap 接口还提供了一个用于返回倒序 map 的方法,方法声明如下所示:

  1. NavigableMap<K,V> descendingMap();

最后, NavigableMap 接口还新增了如下几个实用方法:

  1. Map.Entry<K,V> firstEntry();
  2. Map.Entry<K,V> lastEntry();
  3. Map.Entry<K,V> pollFirstEntry();
  4. Map.Entry<K,V> pollLastEntry();