In this shot we will learn how to use the NavigableSet.descendingSet()
method in Java.
NavigableSet.descendingSet()
methodThe descendingSet()
method is present in the NavigableSet
interface inside the java.util
package.
The NavigableSet.descendingSet()
method is used to obtain the reverse view of the elements present in the set.
NavigableSet
inherits SortedSet
, 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.
NavigableSet
is of string type, the elements get stored in alphabetical order, irrespective of string length.The NavigableSet.descendingSet()
method does not accept any parameters.
The NavigableSet.descendingSet()
method returns the descending order of the element present in the set.
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());}}
From lines 1 to 3, we import the required packages and classes.
In line 4, we make a Main
class.
In line 6, we make a main()
function.
In line 8, we create a TreeSet
of Integer
type. The NavigableSet
is inherited from SortedSet
, which is inherited from TreeSet
only.
As SortedSet
and NavigableSet
are interfaces, we cannot instantiate an object of them.
From lines 10 to 16, we use the add()
method to add the elements to the NavigableSet
.
In line 18, we use the NavigableSet.descendingSet()
method and display the result with a message.