sort treeset in java code example

Example 1: sort treeset in descending order using comparator

//To sort a treeset in descending order just use the descendingSet() method
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);
   }
}

Example 2: java treeset sort

Set<String> set = new TreeSet<String>(new Comparator<String>() {

    public int compare(String one, String other) {
        // implement
    }

});

Example 3: treeset java descending order using comparator

TreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()
  {
  public int compare(Integer i1,Integer i2)
        {
        return i2.compareTo(i1);
        }
  });

Tags:

Java Example