Skip to content

Reverse Elements Order in TreeSet in Java

This example shows how to reverse the order of the TreeSet elements in Java. The example also shows how to iterate the TreeSet in reverse order using the descendingSet or descendingIterator methods.

How to reverse the order of TreeSet elements in Java?

There are several ways using which we can reverse the order of the TreeSet elements or simply iterate the elements in reverse order in Java.

1. Using the descendingSet method (Java 1.6 and later)

Java version 1.6 introduced the descendingSet method that returns a reverse order view of the elements contained in the TreeSet object.

Once we get the reverse set, we can iterate through it using an iterator as given below.

Output

Important Note: The reverse Set returned by the descendingSet method is just a view and is backed by the original TreeSet object. So any changes you make to the original TreeSet object will be reflected in the reverse set, and vice versa.

2. Using the descendingIterator method (Java 1.6 and later versions)

Along with the descendingSet method, Java 1.6 also introduced the descendingIterator method.

Instead of returning a set view, this method returns an iterator over the elements of the TreeSet in reverse order.

Output

3. Using the reverseOrder method of the Collections class

The reverseOrder of the Collections class returns a Comparator that reverses the natural ordering of the elements.

The natural ordering of an object is defined by implementing the Comparable interface and defining the compareTo method.

The below given example shows how to sort TreeSet elements in descending order or reverse order using this method.

Output

As we can see from the output, the TreeSet object has sorted the elements in descending order.

Important Note:

The first two approaches did not change the order of the original TreeSet. The elements were still stored in the TreeSet in their natural ordering while this approach changes the order in which the elements are stored in the TreeSet object itself.

How to change the Comparator to return a descending order?

Suppose you already have a custom comparator that defines the TreeSet ordering and you want to change that to return the reverse order as given below.

Output

We can reverse the order of the elements by simply flipping the arguments subject1 and subject2 as given below to return the elements in the descending order.

Output

We can also put a minus sign instead of flipping the arguments to return the descending order as given below.

Output

Please also visit how to iterate over TreeSet elements to know more.

This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.