What is the NavigableSet.descendingSet() method in Java?
Overview
In this shot we will learn how to use the NavigableSet.descendingSet() method in Java.
The NavigableSet.descendingSet() method
-
The
descendingSet()method is present in theNavigableSetinterface inside thejava.utilpackage. -
The
NavigableSet.descendingSet()method is used to obtain the reverse view of the elements present in the set. -
NavigableSetinheritsSortedSet, meaning elements get stored in the sorted format, so the reverse view indicates descending order of the elements present in the set.
Note: When we add the elements in the
NavigableSet, they get stored in the sorted form.
- If the
NavigableSetis of string type, the elements get stored in alphabetical order, irrespective of string length.
Parameters
The NavigableSet.descendingSet() method does not accept any parameters.
Return value
The NavigableSet.descendingSet() method returns the descending order of the element present in the set.
Code
Let’s take a look at the code below.
import java.util.NavigableSet;import java.util.TreeSet;import java.util.*;class Main {public static void main(String[] args) {NavigableSet<Integer> s = new TreeSet<Integer>();s.add(6);s.add(8);s.add(5);s.add(3);s.add(9);s.add(10);s.add(17);System.out.print("The resultant set after using NavigableSet.descendingSet() is");System.out.println(s.descendingSet());}}
Explanation
-
From lines 1 to 3, we import the required packages and classes.
-
In line 4, we make a
Mainclass. -
In line 6, we make a
main()function. -
In line 8, we create a
TreeSetofIntegertype. TheNavigableSetis inherited fromSortedSet, which is inherited fromTreeSetonly. -
As
SortedSetandNavigableSetare interfaces, we cannot instantiate an object of them. -
From lines 10 to 16, we use the
add()method to add the elements to theNavigableSet. -
In line 18, we use the
NavigableSet.descendingSet()method and display the result with a message.