Iterate LinkedHashMap in Reverse Order Java Example

This example shows how to iterate LinkedHashMap in reverse order in Java. This example also shows various ways to iterate LinkedHashMap in backward direction using ListIterator and descendingIterator method.

How to iterate LinkedHashMap in reverse order in Java?

There are a couple of ways using which you can iterate the LinkedHashMap in reverse or backward direction in Java.

1. Using the ListIterator

In this approach, we will first get all the keys from the LinkedHashMap object using the keySet method. We will then convert the Set to ArrayList using the ArrayList constructor. Once we get the list, we will use the ListIterator to iterate the keys in reverse order using the hasPrevious and previous methods of the ListIterator and get corresponding values from the LinkedHashMap object.

Output

2. Using the descendingIterator method

This approach is similar to the above one, but instead of ArrayList, we will convert Set to a LinkedList object. The descendingIterator method of the LinkedList class will allow us to iterate the keys in the reverse order as given below.

Output

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

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

References:
Java 8 LinkedHashMap

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 *