How to sort TreeSet in descending order in Java?

Java 8Object Oriented ProgrammingProgramming

To sort TreeSet in descending order, use the descendingSet() method in Java.

The descendingSet() method is used to return a reverse order view of the elements contained in this set.

At first, create a TreeSet −

TreeSet<Object> treeSet = new TreeSet<Object>();

Then add some elements −

treeSet.add(45);
treeSet.add(15);
treeSet.add(99);
treeSet.add(70);

Sort them indecreasing order −

TreeSet<Object> res = (TreeSet<Object>)treeSet.descendingSet();

Following is the code to sort TreeSet in descending order −

Example

 Live Demo

import java.util.TreeSet;
public class Main {
   public static void main(String[] args) {
      TreeSet<Object> treeSet = new TreeSet<Object>();
      treeSet.add(45);
      treeSet.add(15);
      treeSet.add(99);
      treeSet.add(70);
      treeSet.add(65);
      treeSet.add(30);
      treeSet.add(10);
      treeSet.add(60);
      treeSet.add(80);
      System.out.println("TreeSet\n" + treeSet);
      TreeSet<Object> res = (TreeSet<Object>)treeSet.descendingSet();
      System.out.println("TreeSet after sorting in descending order\n" + res);
   }
}

Output

TreeSet
[10, 15, 30, 45, 60, 65, 70, 80, 99]
TreeSet after sorting in descending order
[99, 80, 70, 65, 60, 45, 30, 15, 10]
raja
Published on 20-Sep-2019 10:57:08
Advertisements