Java NavigableMap Interface

http‮/:s‬/www.theitroad.com

In Java, the NavigableMap interface is a subinterface of the SortedMap interface that extends the capabilities of a SortedMap by providing navigation methods for accessing entries based on their relative position in the map. The NavigableMap interface provides methods for finding and manipulating entries in the map based on their keys, such as floorEntry(), ceilingEntry(), lowerEntry(), higherEntry(), and pollFirstEntry().

Here are some of the key methods of the NavigableMap interface:

  • Map.Entry<K, V> lowerEntry(K key): Returns a key-value mapping associated with the greatest key less than the specified key, or null if there is no such key.

  • K lowerKey(K key): Returns the greatest key less than the specified key, or null if there is no such key.

  • Map.Entry<K, V> floorEntry(K key): Returns a key-value mapping associated with the greatest key less than or equal to the specified key, or null if there is no such key.

  • K floorKey(K key): Returns the greatest key less than or equal to the specified key, or null if there is no such key.

  • Map.Entry<K, V> ceilingEntry(K key): Returns a key-value mapping associated with the least key greater than or equal to the specified key, or null if there is no such key.

  • K ceilingKey(K key): Returns the least key greater than or equal to the specified key, or null if there is no such key.

  • Map.Entry<K, V> higherEntry(K key): Returns a key-value mapping associated with the least key greater than the specified key, or null if there is no such key.

  • K higherKey(K key): Returns the least key greater than the specified key, or null if there is no such key.

  • Map.Entry<K, V> firstEntry(): Returns a key-value mapping associated with the least key in the map, or null if the map is empty.

  • Map.Entry<K, V> lastEntry(): Returns a key-value mapping associated with the greatest key in the map, or null if the map is empty.

  • Map.Entry<K, V> pollFirstEntry(): Removes and returns a key-value mapping associated with the least key in the map, or null if the map is empty.

  • Map.Entry<K, V> pollLastEntry(): Removes and returns a key-value mapping associated with the greatest key in the map, or null if the map is empty.

NavigableMap has a single concrete implementation in the Java standard library, which is TreeMap. TreeMap is a red-black tree-based implementation of the NavigableMap interface that provides efficient log(n) time cost for the containsKey(), get(), put(), and remove() operations. It also provides efficient methods for navigating the map based on the keys, making it a good choice for sorted map implementations that require navigation capabilities.