Java TreeMap descendingKeySet() 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.

Signature

public NavigableSet descendingKeySet()

This method returns a reverse order NavigableSet view of the keys contained in this map. The set’s iterator returns the keys in descending order.

Example

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

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

public class DescendingKeySetMethodTreeMapExample 
{
    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 descendingKeySet
        NavigableSet ns = treeMap1.descendingKeySet();
        //Elements of the NavigableSet
        System.out.println("**Elements of the NavigableSet**");
        System.out.println(ns);
    }
}

Output

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

Leave a Reply

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