How to sort TreeSet in descending order in Java?

Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order).

Examples:

Input : Set: [2, 3, 5, 7, 10, 20]
Output : Set: [20, 10, 7, 5, 3, 2]

Input : Set: [computer, for, geeks, hello]
Output : Set: [hello, geeks, for, computer]

Approach:
To make a TreeSet Element in decreasing order, simple use descendingSet() method which is used to change the order of TreeSet in reverse order



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to print TreeSet in reverse Order
import java.util.TreeSet;
  
public class TreeSetDescending {
  
    public static void main(String[] args)
    {
        // Declare a treeset
        TreeSet<Object> ints = new TreeSet<Object>();
        ints.add(2);
        ints.add(20);
        ints.add(10);
        ints.add(5);
        ints.add(7);
        ints.add(3);
  
        // Initialize treeset with predefined set in reverse order
        // using descendingSet()
        TreeSet<Object> intsReverse = (TreeSet<Object>)ints.descendingSet();
  
        // Print the set
        System.out.println("Without descendingSet(): " + ints);
        System.out.println("With descendingSet(): " + intsReverse);
    }
}

chevron_right


Output:

Without descendingSet(): [computer, for, geeks, hello]
With descendingSet(): [hello, geeks, for, computer]


My Personal Notes arrow_drop_up

सर्वशक्तिशाली इकलौता

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.