Skip to content
Related Articles
Open in App
Not now

Related Articles

Reversing Elements Order in TreeSet in Java Using the descendingIterator Method

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 17 Dec, 2020
Improve Article
Save Article

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!