Wednesday, July 3, 2024
HomeLanguagesJavaReversing Elements Order in TreeSet in Java Using the descendingIterator Method

Reversing Elements Order in TreeSet in Java Using the descendingIterator Method

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

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments