Java TreeMap descendingMap() Method Example

The descendingKeySet() method of java.util.TreeMap class returns a reverse order NavigableSet view of the keys contained in this map whereas descendingMap() method returns a reverse order view of the mappings contained in this map.

Signature

public NavigableMap<K,V> descendingMap()

This method returns a reverse order view of the mappings contained in this map.

Example

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

import java.util.NavigableMap;
import java.util.TreeMap;

public class DescendingMapMethodTreeMapExample
{
    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 descendingMap
        NavigableMap nm = treeMap1.descendingMap();
        //Elements of the NavigableMap
        System.out.println("**Elements of the NavigableMap**");
        System.out.println(nm);
    }
}

Output

**Elements of the NavigableMap**
{5=Element5, 4=Element4, 3=Element3, 2=Element2, 1=Element1}

Leave a Reply

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