sort treeset in descending order using comparator

Solutions on MaxInterview for sort treeset in descending order using comparator by the best coders in the world

showing results for - "sort treeset in descending order using comparator"
Bernie
19 Jun 2020
1//To sort a treeset in descending order just use the descendingSet() method
2import java.util.TreeSet;
3public class Main {
4   public static void main(String[] args) {
5      TreeSet<Object> treeSet = new TreeSet<Object>();
6      treeSet.add(45);
7      treeSet.add(15);
8      treeSet.add(99);
9      treeSet.add(70);
10      treeSet.add(65);
11      treeSet.add(30);
12      treeSet.add(10);
13      treeSet.add(60);
14      treeSet.add(80);
15      System.out.println("TreeSet\n" + treeSet);
16      TreeSet<Object> res = (TreeSet<Object>)treeSet.descendingSet();
17      System.out.println("TreeSet after sorting in descending order\n" + res);
18   }
19}
Luka
05 Sep 2019
1TreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()
2  {
3  public int compare(Integer i1,Integer i2)
4        {
5        return i2.compareTo(i1);
6        }
7  });