NavigableMap in Java 6 is an extension of SortedMap like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey. All of these methods also provides a boolean to include specified key or not. TreeMap and ConcurrentSkipListMap are two concrete implementation of NavigableMap in Java 1.6 API. Though NavigableMap is not as popular as HashMap, ConcurrentHashMap or Hashtable but given that TreeMap implements NavigableMap you already get all good things in a well known Map implementation.
How to use NavigableMap in Java - Example
In this Java tutorial we will explore some API methods of NavigableMap to show its functionality. This Java program shows example of lowerKey which returns keys less than specified, floorKey returns key less than or equal to, ceilingKey return greater than or equal to and higherKey which returns keys which are greater than specified key. This Java example also demonstrate use of headMap(), tailMap() and subMap() method which is used to create Map from an existing Map in Java. headMap returns a Map whose keys are lower than specified keys while tailMap returns Map which contains keys, those are higher than specified. Here is complete code example of How to use NavigableMap in Java.
That's all on What is NavigableMap in Java and How to use NavigableMap with example. We have seen examples of popular navigation method on TreeMap e.g. floorKey. You can also use similar method like lowerEntry, floorEntry, ceilingEntry and higherEntry to retrieve Entry instead of key. NavigableMap is also a good utility to create subset of a Map in Java.
Other Java Collection tutorials from Javarevisited blog