Skip to content

Iterate TreeMap in Reverse Order in Java Example

This example shows how to iterate Java TreeMap in reverse order. The example also shows how to iterate TreeMap in reverse order using the reverseOrder, descendingKeySet, and descendingMap methods.

How to iterate TreeMap in reverse order in Java?

There are several ways using which you can iterate the TreeMap object in the reverse direction as given below.

1. Using the reverseOrder method of the Collections class

The reverseOrder method of the Collections class returns a Comparator that imposes the reverse of the natural ordering of the objects. We can then use this comparator object in the constructor of the TreeMap to create an object that stores the mapping in the reverse order of the keys.

Output

Note: The above given approach works at the TreeMap object creation time. If you have an existing map object that is not created using the reverseOrder method, you can use the below given approaches to iterate the map in reverse order.

2. Using the descendingKeySet method of the TreeMap class

The descendingKeySet method returns a reverse order Set view of the keys contained in the TreeMap object.

The iterator of the set view returns the TreeMap keys in the descending order.

Output

Important Note:

The key set returned by the descendingKeySet method is a view and it is backed by the original TreeMap object. Any changes you make to this view will be reflected to the original TreeMap object and vice versa.

Plus, this set view does not support add and addAll operations. If you call the add or addAll method on the set view, the code will throw java.lang.UnsupportedOperationException exception.

3. Using the descendingMap method of the TreeMap class

The descendingMap method of the TreeMap class returns a map containing reverse view of the mappings contained in this TreeMap object.

Once you get this map, you can iterate through the entries using the iterator of the entry set.

Output

Note: The descending map returned by the descendingMap method is a view so any changes you make will be reflected in the original TreeMap and vice versa.

This example is a part of the TreeMap in Java Tutorial.

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

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.