treeset in descending order java code example

Example 1: TreeSet descendingIterator() method in java

TreeSet descendingIterator() method for String value.
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDescendingIteratorMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeSet<String> ts = new TreeSet<String>();
         ts.add("Ajay");
         ts.add("Bharat");
         ts.add("Chetan");
         ts.add("Dinesh");
         System.out.println("TreeSet: " + ts);
         // create descending iterator using descendingIterator() method
         Iterator<String> iterate = ts.descendingIterator();
         System.out.println("Values using descendingIterator() method: ");
         while(iterate.hasNext())
         {
            System.out.println(iterate.next());
         }
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Example 2: TreeSet descendingSet() method in java

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
public class TreeSetDescendingSetMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeSet<String> ts = new TreeSet<String>();
         ts.add("Apple");
         ts.add("Banana");
         ts.add("Cherry");
         ts.add("Dragon Fruit");
         System.out.println("TreeSet: " + ts);
         // reverse order view of element using descendingSet() method
         NavigableSet<String> ns = ts.descendingSet();
         Iterator<String> iterate = ns.iterator();
         System.out.println("Values using descendingSet() method: ");
         while(iterate.hasNext())
         {
            System.out.println(iterate.next());
         }
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Example 3: 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);
   }
}

Tags:

Java Example