How to sort treeset in descending order in java

Let’s learn how to sort treeset in descending order in java.

How to sort treeset in descending order in java

In this post lets sort treeset elements in descending order or decreasing order.

import java.util.TreeSet;
public class TreeSetExample 
{
   public static void main(String[] args) 
   {
      TreeSet<Object> number = new TreeSet<Object>(); 
      number.add(1); 
      number.add(24); 
      number.add(15); 
      number.add(6); 
      number.add(9); 
      number.add(2);
      // reverse order using descendingSet()
      TreeSet<Object> reverseOrder = (TreeSet<Object>)number.descendingSet();
      // printing set 
      System.out.println("Without using descendingSet() method: " + number); 
      System.out.println("Using descendingSet() method: " + reverseOrder);
   }
}


Output:

Without using descendingSet() method: [1, 2, 6, 9, 15, 24]
Using descendingSet() method: [24, 15, 9, 6, 2, 1]


Also read – static keyword in java