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.
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.
Input : TreeSet = [2, 5, 6] Output: Reverse = [6, 5, 2] Input : TreeSet = [a, b, c] Output: Reverse =
public Iterator descendingIterator()
Return Value: This method returns an iterator over the elements in this set in descending order.
- Create iterator variable and initialize it with the return value of descendingIterator() method.
- Iterate the iterator variable using while loop.
- Print the values during the loop.
Below is the implementation of the above approach:
TreeSet(setOfNumbers) : [1, 2, 4, 5, 7] TreeSet in reverse order : 7 5 4 2 1