TreeSet descendingIterator() method in java

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

TreeSet descendingIterator() method in java

descendingIterator() method of TreeSet class returns an iterator over the elements in this set in descending order.

Syntax:

public Iterator<E> descendingIterator()

Also read – TreeSet in java

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

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDescendingIteratorMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeSet<Integer> ts = new TreeSet<Integer>();
         ts.add(50);
         ts.add(60);
         ts.add(70);
         ts.add(80);
         System.out.println("TreeSet: " + ts);
         // create descending iterator using descendingIterator() method
         Iterator<Integer> 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);
      }
   }
}


Output:

TreeSet: [50, 60, 70, 80]
Values using descendingIterator() method:
80
70
60
50


Let’s see example on 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);
      }
   }
}


Output:

TreeSet: [Ajay, Bharat, Chetan, Dinesh]
Values using descendingIterator() method:
Dinesh
Chetan
Bharat
Ajay