Skip to content
Related Articles

Related Articles

TreeMap descendingKeySet() Method in Java with Examples
  • Last Updated : 27 Aug, 2020

The descendingKeySet() method of TreeMap class returns a reverse order NavigableSet view of the keys contained within the map. The iterator of the set returns the keys in descending order. 

Note: The set is backed by the map, so changes to the map are reflected within the set, and vice-versa.

Syntax:

public NavigableSet<K> descendingKeySet()

Parameters: The method does not take any parameters.

Return Value: The method returns a navigable set view of the values contained in the map.



Exception: The method does not throw any exceptions.

Example 1: 
 

Java




// Java Program to show the working
// of descendingKeySet() Method
import java.io.*;
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // creating tree map of Integer and String
        TreeMap<Integer, String> treemap
            = new TreeMap<Integer, String>();
  
        // populating tree map using put()
        treemap.put(3, "three");
        treemap.put(1, "one");
        treemap.put(2, "two");
        treemap.put(0, "zero");
        treemap.put(7, "seven");
        treemap.put(6, "six");
  
        // putting values in navigable set
        // use of descendingKeySet
        NavigableSet set1 = treemap.descendingKeySet();
  
        System.out.println("Navigable set values are: "
                           + set1);
    }
}

Output: 

Navigable set values are: [7, 6, 3, 2, 1, 0]

Example 2: 
 

Java




// Java Program to show the working
// of descendingKeySet() Method
import java.io.*;
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // creating tree map of Integer and String
        TreeMap<Integer, String> geeks
            = new TreeMap<Integer, String>();
  
        // putting values in navigable set
        geeks.put(1, "Guru");
        geeks.put(2, "Ayush");
        geeks.put(3, "Devesh");
        geeks.put(4, "Kashish");
  
        System.out.println("TreeMap values :- " + geeks);
  
        // use of descendingKeySet
        NavigableSet nevigableSet
            = geeks.descendingKeySet();
  
        System.out.println("Reverse key values:- "
                           + nevigableSet);
    }
}

Output: 
 

TreeMap values :- {1=Guru, 2=Ayush, 3=Devesh, 4=Kashish}
Reverse key values:- [4, 3, 2, 1]

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :