Java TreeMap navigableKeySet() Method Example

The descendingKeySet() method of java.util.TreeMap class returns a reverse order NavigableSet view of the keys contained in this map. The set’s iterator returns the keys in descending order whereas navigableKeySet() returns a NavigableSet view of the keys contained in this map. The set’s iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Signature

public NavigableSet<K> navigableKeySet()

This method returns a NavigableSet view of the keys contained in this map. The set’s iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Example

The following example shows the usage of java.util.TreeMap.navigableKeySet() method.

import java.util.NavigableSet;
import java.util.TreeMap;

public class NavigableKeySetMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Get the navigableKeySet
        NavigableSet ns = treeMap1.navigableKeySet();
        //Elements of the NavigableSet
        System.out.println("**Elements of the NavigableKeySet**");
        System.out.println(ns);
    }
}

Output

**Elements of the NavigableSet**
[1, 2, 3, 4, 5]

Leave a Reply

Your email address will not be published. Required fields are marked *