Java TreeSet descendingIterator() Example

In this tutorial we will learn how to iterate a TreeSet in descending order. we will use descendingIterator() method of java.util.TreeSet class to perform this.

Signature

public Iterator<E> descendingIterator() 

Returns an iterator over the elements in this set in descending order.

Example

The following example shows the usage of java.util.TreeSet.descendingIterator() method.

import java.util.Iterator;
import java.util.TreeSet;

public class DescendingIteratorMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet  treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        
        //Printing the elements of the TreeSet in actual order
        System.out.println("**Before Reversing**");
        Iterator iterator1 = treeSet1.iterator();
        while(iterator1.hasNext())
        {
            System.out.println(iterator1.next());
        }
        
        //Iterating the TreeSet in the descending order
        System.out.println("After Reversing");
        Iterator iterator2 = treeSet1.descendingIterator();
        while(iterator2.hasNext())
        {
            System.out.println(iterator2.next());
        }
        
    }
}

Output

**Before Reversing**
Element1
Element2
Element3
**After Reversing**
Element3
Element2
Element1

Leave a Reply

Your email address will not be published. Required fields are marked *