Skip to content

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

Leave a Reply

Your email address will not be published.