Java TreeSet - descendingSet() Method
The java.util.TreeSet.descendingSet() method returns a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa.
Syntax
public NavigableSet<E> descendingSet()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns a reverse order view of this set.
Exception
NA
Example:
In the example below, the java.util.TreeSet.descendingSet() method returns a reverse order view of the given treeset.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating treesets TreeSet<Integer> MySet = new TreeSet<Integer>(); TreeSet<Integer> Reverse_MySet = new TreeSet<Integer>(); //populating the set MySet.add(40); MySet.add(20); MySet.add(10); MySet.add(30); //printing MySet System.out.println("MySet contains: " + MySet); //creating reverse set Reverse_MySet = (TreeSet<Integer>)MySet.descendingSet(); //printing Reverse_MySet System.out.println("Reverse_MySet contains: " + Reverse_MySet); } }
The output of the above code will be:
MySet contains: [10, 20, 30, 40] Reverse_MySet contains: [40, 30, 20, 10]
❮ Java.util - TreeSet