NavigableMap Interface in Java with Example

21 Nov, 2021
The NavigableMap interface is a member of the Java Collection Framework. It belongs to java.util package and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey, and along with this 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 the specified key, tailMap whose keys are greater than the specified key, and a subMap which strictly contains keys which fall between toKey and fromKey. An example class that implements NavigableMap is TreeMap.
Declaration:
public interface NavigableMap<K,V> extends SortedMap<K,V>
Here, K is the key Object type and V is the value Object type.
Hierarchy of NavigableMap
It implements Map<K,V>, SortedMap<K,V> interfaces. ConcurrentNavigableMap<K,V> extends NavigableMap. ConcurrentSkipListMap and TreeMap implements NavigableMap.
Example:
Java
// Java program to demonstrate// the NavigableMap interfaceimport java.util.NavigableMap;import java.util.TreeMap; public class NavigableMapExample {     public static void main(String[] args)    {        // Instantiate an object        // Since NavigableMap        // is an interface so we        // use TreeMap        NavigableMap<String, Integer> nm            = new TreeMap<String, Integer>();         // Add elements using put() method        nm.put("C", 888);        nm.put("Y", 999);        nm.put("A", 444);        nm.put("T", 555);        nm.put("B", 666);        nm.put("A", 555);         // Print the contents on the console        System.out.println("Mappings of NavigableMap : "                           + nm);         System.out.printf("Descending Set  : %s%n",                          nm.descendingKeySet());        System.out.printf("Floor Entry  : %s%n",                          nm.floorEntry("L"));        System.out.printf("First Entry  : %s%n",                          nm.firstEntry());        System.out.printf("Last Key : %s%n", nm.lastKey());        System.out.printf("First Key : %s%n",                          nm.firstKey());        System.out.printf("Original Map : %s%n", nm);        System.out.printf("Reverse Map : %s%n",                          nm.descendingMap());    }}
 Output:
Mappings of NavigableMap : {A=555, B=666, C=888, T=555, Y=999}
Descending Set  : [Y, T, C, B, A]
Floor Entry  : C=888
First Entry  : A=555
Last Key : Y
First Key : A
Original Map : {A=555, B=666, C=888, T=555, Y=999}
Reverse Map : {Y=999, T=555, C=888, B=666, A=555}
The NavigableMap has two implementing classes which are ConcurrentSkipListMap and TreeMap. TreeMap is a Red-Black tree based NavigableMap implementation and it is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.  The TreeMap has the expected time cost of log(n) for insertion, deletion, and access operations. TreeMap is not synchronized and it has to be done externally.
Syntax:
NavigableMap<K, V> objectName = new TreeMap<K, V>();
1. Adding Elements
To add elements to a NavigableMap we can use any methods of the Map interface. The code below shows how to use them. You can observe in the code that the insertion order is not retained. When no Comparator is provided at the time of construction, the natural order is followed. 
Java
// Java program for adding elements// to a NavigableMapimport java.util.*; class AddingElementsExample {    public static void main(String args[])    {         // Instantiate an object        // Since NavigableMap is an interface        // We use TreeMap        NavigableMap<Integer, String> nmap            = new TreeMap<Integer, String>();         // Add elements using put()        nmap.put(3, "Geeks");        nmap.put(2, "For");        nmap.put(1, "Geeks");         // Print the contents on the console        System.out.println("Mappings of NavigableMap : "                           + nmap);    }}
 Output:
Mappings of NavigableMap : {1=Geeks, 2=For, 3=Geeks}
2. Removing Elements
To remove elements as well we use methods of the Map interface, as NavigableMap is a descendant of Map. We can use the remove() method that takes the key value and removes the mapping for the key from this treemap if it is present on the map. We can use clear() to remove all the elements of the map. 
Java
// Java Program for deleting// elements from NavigableMapimport java.util.*; class RemovingElementsExample {       public static void main(String args[])    {        // Instantiate an object        // Since NavigableMap        // is an interface        // We use TreeMap        NavigableMap<Integer, String> nmap            = new TreeMap<Integer, String>();         // Add elements using put()        nmap.put(3, "Geeks");        nmap.put(2, "Geeks");        nmap.put(1, "Geeks");        nmap.put(4, "For");         // Print the contents on the console        System.out.println("Mappings of NavigableMap : "                           + nmap);         // Remove elements using remove()        nmap.remove(4);         // Print the contents on the console        System.out.println(            "\nNavigableMap, after remove operation : "            + nmap);         // Clear the entire map using clear()        nmap.clear();        System.out.println(            "\nNavigableMap, after clear operation : "            + nmap);    }}
 Output:
Mappings of NavigableMap : {1=Geeks, 2=Geeks, 3=Geeks, 4=For}

NavigableMap, after remove operation : {1=Geeks, 2=Geeks, 3=Geeks}

NavigableMap, after clear operation : {}
3. Accessing the Elements
We can access the elements of a NavigableMap using get() method, the example of this is given below.
Java
// Java Program for accessing// elements in a NavigableMap import java.util.*; public class AccessingElementsExample {     public static void main(String[] args)    {        // Instantiate an object        // Since NavigableMap is an interface        // We use TreeMap        NavigableMap<Integer, String> nmap            = new TreeMap<Integer, String>();         // Add elements using put()        nmap.put(8, "Third");        nmap.put(6, "Second");        nmap.put(3, "First");        nmap.put(11, "Fourth");         // Accessing the elements using get()        // with key as a parameter        System.out.println(nmap.get(3));        System.out.println(nmap.get(6));        System.out.println(nmap.get(8));        System.out.println(nmap.get(11));         // Display the set of keys using keySet()        System.out.println("\nThe NavigableMap key set: "                           + nmap.keySet());    }}
 Output:
First
Second
Third
Fourth

The NavigableMap key set: [3, 6, 8, 11]
4. Traversing
We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the NavigableMap. Another famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.
Java
// Java Program for traversing// a NavigableMapimport java.util.*; class TraversalExample {       public static void main(String args[])    {        // Instantiate an object        // Since NavigableMap is an interface        // We use TreeMap        NavigableMap<Integer, String> nmap            = new TreeMap<Integer, String>();         // Add elements using put()        nmap.put(3, "Geeks");        nmap.put(2, "For");        nmap.put(1, "Geeks");         // Create an Iterator over the        // NavigableMap        Iterator<NavigableMap.Entry<Integer, String> > itr            = nmap.entrySet().iterator();         System.out.println("Traversing using Iterator: ");        // The hasNext() method is used to check if there is        // a next element The next() method is used to        // retrieve the next element        while (itr.hasNext()) {            NavigableMap.Entry<Integer, String> entry                = itr.next();            System.out.println("Key = " + entry.getKey()                               + ", Value = "                               + entry.getValue());        }         System.out.println("Traversing using for-each: ");        // Iterate using for-each loop        for (Map.Entry mapElement : nmap.entrySet()) {            // get the key using getKey()            int key = (int)mapElement.getKey();             // Finding the value            String value = (String)mapElement.getValue();             System.out.println("Key = " + key                               + ", Value = " + value);        }    }}
 Output:
Traversing using Iterator:  
Key = 1, Value = Geeks
Key = 2, Value = For
Key = 3, Value = Geeks
Traversing using for-each:  
Key = 1, Value = Geeks
Key = 2, Value = For
Key = 3, Value = Geeks
Note: Every time that we say ‘elements of NavigableMap’, it has to be noted that the elements are actually stored in the object of an implementing class of NavigableMap in this case TreeMap.
NavigableMap inherits methods from the Map interface, SortedMap interface. The basic methods for adding elements, removing elements, and traversal are given by the parent interfaces. The methods of the NavigableMap are given in the following table. Here,
K – The type of the keys in the map.
V – The type of values mapped in the map.
METHOD
DESCRIPTION
subMap(K fromKey, boolean 
fromInclusive, K toKey, boolean toInclusive)
METHOD
DESCRIPTION
METHOD
DESCRIPTION
compute(K key, BiFunction<? super K,? super 
V,? extends V> remappingFunction)
computeIfAbsent(K key, Function<? super K,? 
extends V> mappingFunction)
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ganeshchowdharysadanala
kapoorsagar226
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Introduction to Java