TreeSet descendingSet() method in java

Let’s learn TreeSet descendingSet() method in java.

TreeSet descendingSet() method in java

descendingSet() method of TreeSet class returns a reverse order view of the elements contained in this set.

The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa.

Syntax:

public NavigableSet<E> descendingSet()

Returns:

a reverse order view of this set.

Also read – TreeSet in java

Now let’s see example on TreeSet descendingSet() method.

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);
      }
   }
}


Output:

TreeSet: [Apple, Banana, Cherry, Dragon Fruit]
Values using descendingSet() method:
Dragon Fruit
Cherry
Banana
Apple