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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping