Java Utility Library

Java TreeMap - descendingMap() Method



The java.util.TreeMap.descendingMap() method returns a reverse order view of the mappings contained in this map. The descending map is backed by this map, so changes to the map are reflected in the descending map, and vice-versa.

Syntax

public NavigableMap<K,V> descendingMap()

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

No parameter is required.

Return Value

Returns a reverse order view of this map.

Exception

NA.

Example:

In the example below, the java.util.TreeMap.descendingMap() method returns a reverse order view of the mappings contained in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> Map1 = new TreeMap<Integer, String>();

    //populating Map1
    Map1.put(102, "John");
    Map1.put(103, "Marry");
    Map1.put(101, "Kim");
    Map1.put(104, "Jo");
    Map1.put(105, "Sam");

    //printing the Map1
    System.out.println("Map1 contains: " + Map1); 

    //creating a reverse order view of mapping
    NavigableMap<Integer, String> Map2 = Map1.descendingMap(); 

    //printing the Map2
    System.out.println("Map2 contains: " + Map2);         
  }
}

The output of the above code will be:

Map1 contains: {101=Kim, 102=John, 103=Marry, 104=Jo, 105=Sam}
Map2 contains: {105=Sam, 104=Jo, 103=Marry, 102=John, 101=Kim}

❮ Java.util - TreeMap