Skip to content
Related Articles

Related Articles

Reversing Elements Order in TreeSet in Java Using the descendingIterator Method
  • Difficulty Level : Hard
  • Last Updated : 17 Dec, 2020
GeeksforGeeks - Summer Carnival Banner

The descendingIterator() method of java.util.TreeSet<E> class is used to return an iterator over the elements in the set in descending order. Once the iterator assigns with the return value of the descendingIterator(), iterate the iterator using while loop.

Example: 

Input : TreeSet = [2, 5, 6]
Output: Reverse = [6, 5, 2]

Input : TreeSet = [a, b, c]
Output: Reverse = 

Syntax:

public Iterator descendingIterator()

Return Value: This method returns an iterator over the elements in this set in descending order.

Approach:



  1. Create iterator variable and initialize it with the return value of descendingIterator() method.
  2. Iterate the iterator variable using while loop.
  3. Print the values during the loop.

Below is the implementation of the above approach:

Java




// Reversing Elements Order in TreeSet in
// Java Using the descendingIterator Method
import java.util.Iterator;
import java.util.TreeSet;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating TreeSet and adding value to it
        TreeSet<Integer> setOfNumbers
            = new TreeSet<Integer>();
  
        setOfNumbers.add(2);
        setOfNumbers.add(5);
        setOfNumbers.add(1);
        setOfNumbers.add(7);
        setOfNumbers.add(4);
  
        // Printing TreeSet Elements
        System.out.println("TreeSet(setOfNumbers) : "
                           + setOfNumbers);
  
        Iterator<Integer> iterator
            = setOfNumbers.descendingIterator();
  
        // Iterating TreeSet
        System.out.print("TreeSet in reverse order : ");
  
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}
Output
TreeSet(setOfNumbers) : [1, 2, 4, 5, 7]
TreeSet in reverse order : 7 5 4 2 1

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :