What is the TreeMap.descendingMap() method in Java?

In this shot, we will learn how to use the TreeMap.descendingMap() method in Java.

Introduction

The TreeMap.descendingMap() method is present in the NavigableMap interface inside the java.util package. TreeMap implements the NavigableMap interface.

The TreeMap.descendingMap() method is used to obtain the reverse view of the elements present in the TreeMap.

Syntax

The syntax of the TreeMap.descendingMap() is shown below:

NavigableMap descendingMap();

Parameters

The TreeMap.descendingMap() method does not accept any parameters.

Return value

The TreeMap.descendingMap() method returns a reverse view of the elements present in the NavigableMap.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer,String> s = new TreeMap<Integer,String>();
s.put(6,"Learn");
s.put(8,"in-demand");
s.put(5,"tech");
s.put(3,"skills");
s.put(9,"at");
s.put(10,"Educative.io");
NavigableMap y = s.descendingMap();
System.out.println("The resultant map after using" +
"TreeMap.descendingMap() is: " + y);
}
}

Explanation

  • In line 1, we import the required package.

  • In line 2, we make the Main class.

  • In line 4, we make a main() function.

  • In line 6, we create a TreeMap that contains keys of type Integer and values of type String.

  • From lines 8 to 13, we use the TreeMap.put() method to add the elements into the TreeMap.

  • In line 15, we use the TreeMap.descendingMap() method and display the resultant map with a message in line 16.

So, this is the way to use the TreeMap.descendingMap() method in Java.