Friday, November 15, 2024
Google search engine
HomeLanguagesJavaNavigableMap Interface in Java with Example

NavigableMap Interface in Java with Example

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

NavigableMap Interface in Java with Example

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 interface
import 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}

Implementing Classes

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>();

Basic Operations on NavigableMap

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 NavigableMap
import 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 NavigableMap
import 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 NavigableMap
import 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.

Methods of NavigableMap

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

ceilingEntry(K key) Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
ceilingKey(K key) Returns the least key greater than or equal to the given key, or null if there is no such key.
descendingKeySet() Returns a reverse order NavigableSet view of the keys contained in this map.
descendingMap() Returns a reverse order view of the mappings contained in this map.
firstEntry() Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
floorEntry(K key) Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
floorKey(K key) Returns the greatest key less than or equal to the given key, or null if there is no such key.
headMap(K toKey) Returns a view of the portion of this map whose keys are strictly less than toKey.
headMap(K toKey, boolean inclusive) Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
higherEntry(K key) Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
higherKey(K key) Returns the least key strictly greater than the given key, or null if there is no such key.
lastEntry() Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
lowerEntry(K key) Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
lowerKey(K key) Returns the greatest key strictly less than the given key, or null if there is no such key.
navigableKeySet() Returns a NavigableSet view of the keys contained in this map.
pollFirstEntry() Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollLastEntry() Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

subMap(K fromKey, boolean 

fromInclusive, K toKey, boolean toInclusive)

Returns a view of the portion of this map whose keys range from fromKey to toKey.
subMap(K fromKey, K toKey) Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
tailMap(K fromKey) Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
 tailMap(K fromKey, boolean inclusive) Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.

Methods inherited from interface java.util.SortedMap

METHOD

DESCRIPTION

comparator() Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
entrySet() Returns a Set view of the mappings contained in this map.
firstKey() Returns the first (lowest) key currently in this map.
keySet() Returns a Set view of the keys contained in this map.
lastKey() Returns the last (highest) key currently in this map.
values() Returns a Collection view of the values contained in this map.

Methods inherited from interface java.util.Map

METHOD

DESCRIPTION

clear() Removes all of the mappings from this map (optional operation).

compute(K key, BiFunction<? super K,? super 

V,? extends V> remappingFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

computeIfAbsent(K key, Function<? super K,? 

extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
containsKey(Object key) Returns true if this map contains a mapping for the specified key.
containsValue(Object value) Returns true if this map maps one or more keys to the specified value.
equals(Object o) Compares the specified object with this map for equality.
forEach(BiConsumer<? super K,? super V> action) Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
hashCode() Returns the hash code value for this map.
isEmpty() Returns true if this map contains no key-value mappings.
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
put(K key, V value) Associates the specified value with the specified key in this map (optional operation).
putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map (optional operation).
putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove(Object key) Removes the mapping for a key from this map if it is present (optional operation).
remove(Object key, Object value) Removes the entry for the specified key only if it is currently mapped to the specified value.
replace(K key, V value) Replaces the entry for the specified key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue) Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll(BiFunction<? super K,? super V,? extends V> function) Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
size() Returns the number of key-value mappings in this map.

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html 
This article is contributed by Pratik Agarwal. If you like Lazyroar 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 Lazyroar 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.

RELATED ARTICLES

Most Popular

Recent Comments