How to Iterate LinkedHashMap in Reverse Order in Java?


The LinkedHashMap serves the purpose of maintaining the precise order of element addition. It elucidates the method for accessing elements in the sequence they were inserted.

In addition to storing values based on their keys, the LinkedHashMap class expands upon the functionalities of the Hash Map class and implements the Map interface. It exclusively accommodates unique elements or mappings.

It affords us the flexibility to utilize various data types, such as text, float, integer, etc., for assigning keys and values. By initially reversing the elements, we can alter the order of elements in the linked hash map. Subsequently, we can repeat this process as desired.

Methods Used

A LinkedHashMap can be iterated in reverse order in one of the three methods that follow −

  • Employing listIterator()

  • With the help of reverse()

  • Making use of the descendingIterator()

Method 1: Employing listIterator()

This method provides a list iterator that allows traversal through the elements of a given list in their proper sequence, starting from the specified position within the list.

Syntax

ListIterator listIterator(int index)

The index of the initial element to be returned via the list iterator (through a call to next): This is the only argument that this method accepts.

What does it return? This function provides a list iterator that iterates through each object in turn (in the correct order). That is starting at the provided position within the list.

listIterator()

In this method, we begin by utilizing the "keySet" method to obtain all the keys from the LinkedHashMap object. We then employ the ArrayList constructor to convert the obtained Set into an ArrayList.

Once we have the list, we utilize the "hasPrevious" and "previous" methods of the ListIterator to traverse the keys in reverse order. This enables us to retrieve the corresponding values from the LinkedHashMap object.

Algorithm

  • Step 1 − Create a LinkedHashMap object and add some elements to it.

  • Step 2 − Obtain all the keys from the LinkedHashMap object.

  • Step 3 − Convert the keys to a List object.

  • Step 4 − Create a ListIterator object for the List object.

  • Step 5 − Iterate via the ListIterator object in reverse order. Display the values of the LinkedHashMap object.

Example

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

public class Tutorialspoint {

   public static void main(String[] args) {

      LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>();

      lhmap.put(1, "Google");
      lhmap.put(2, "Firefox");
      lhmap.put(3, "Safari");
      lhmap.put(4, "Brave");
      lhmap.put(5, "Opera");

      // obtain all keys from the LinkedHashMap
      Set<Integer> setKeys = lhmap.keySet();

      List<Integer> listKeys = new ArrayList<Integer>(setKeys);

      ListIterator<Integer> iterator = listKeys.listIterator( listKeys.size() );

      while(iterator.hasPrevious()){
         System.out.println( lhmap.get( iterator.previous() ) );
      }
   }
}

Output

Opera
Brave
Safari
Firefox
Google

Method 2: With the help of reverse()

It is a static approach that the Collections class has defined. Reversing the order of the entries in a List is possible using the reverse() method.

Syntax

public static void reverse(List myList)

The Collections.reverse(myList) function reverses the order of the elements in the list myList.

It doesn't give anything back, but it internally updates the list. An UnsupportedOperationException occurs if the list myList or its list-iterator is unable to support the set operation.

Collections.reverse()

The code demonstrates iterating through a LinkedHashMap in both insertion order and reverse order. It prints the key-value pairs in the LinkedHashMap, first in insertion order, and then in reverse insertion order.

Algorithm

  • Step 1 − Start the program and print "Employee Details:".

  • Step 2 − Create a new LinkedHashMap object named "lhm" with Integer keys and String values.

  • Step 3 − Add key-value pairs to the "lhm" LinkedHashMap.

  • Step 4 − Print "Insertion Order of LinkedHashMap -> iterating".

  • Step 5 − Get the key set from the "lhm" LinkedHashMap using the "keySet" method and store it in the "set" Set.

  • Step 6 − Obtain an iterator from the "set" Set using the "iterator" method.

  • Step 7 − Enter a loop using the "while" statement with the condition "itr.hasNext()" to iterate through the keys in the insertion order.

  • Step 8 − Within the loop, retrieve the next key using "itr.next()" and store it in the "key" variable.

  • Step 9 − Print the key and its corresponding value from the "lhm" LinkedHashMap using "lhm.get(key)".

  • Step 10 − End the loop.

  • Step 11 − Print a new line.

  • Step 12 − Print "Reversing of Insertion Order -> iterating".

  • Step 13 − Create a new ArrayList named "alKeys" and initialize it with the keys from the "lhm" LinkedHashMap using the ArrayList constructor.

  • Step 14 − Reverse the order of the elements in the "alKeys" ArrayList using "Collections.reverse(alKeys)".

  • Step 15 − Iterate over the "alKeys" ArrayList using a for-each loop, with "strKey" as the loop variable.

  • Step 16 − Within the loop, print the key and its corresponding value from the "lhm" LinkedHashMap using "lhm.get(strKey)".

  • Step 17 − End the loop.

  • Step 18 − End the program.

Example

// Java program to iterate LinkedHashMap in reverse order

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

public class Tutorialspoint {

   public static void main(String[] args){
      System.out.println("Employee Details:");

      // generate HashMap object of type <String, String>
      LinkedHashMap<Integer, String> lhm
      = new LinkedHashMap<Integer, String>();

      // adding key-value pairs to HashMap object
      lhm.put(1, "Amy");
      lhm.put(2, "John");
      lhm.put(3, "Paul");

      System.out.println(
      "Sequence of LinkedHashMap Insertions->"
      + " iterating \n");

      // getting keySet() into Set
      Set<Integer> set = lhm.keySet();

      // get Iterator from key set
      Iterator<Integer> itr = set.iterator();

      // iterating as per Insertion Order
      while (itr.hasNext()) {
         Integer key = itr.next();
         System.out.println("Key : " + key + "\t\t" + "Value : " + lhm.get(key));
      }

      // Reverse of Insertion Order iterating
      System.out.println("\n\nReversing of Order of Insertion->"
      + " iterating \n");

      // convert to ArrayList of key set
      List<Integer> alKeys
      = new ArrayList<Integer>(lhm.keySet());

      // reverse order of keys
      Collections.reverse(alKeys);

      // iterate LHM using reverse order of keys
      for (Integer strKey : alKeys) {
         System.out.println("Key : " + strKey + "\t\t" + "Value : " + lhm.get(strKey));
      }
   }
}

Output

Employee Details:
Sequence of LinkedHashMap Insertions-> iterating 

Key : 1		Value : Amy
Key : 2		Value : John
Key : 3		Value : Paul
Reversing of Order of Insertion-> iterating 

Key : 3		Value : Paul
Key : 2		Value : John
Key : 1		Value : Amy

Method 3: Making use of the descendingIterator()

The descendingIterator() method is employed to acquire an iterator that traverses the components within the LinkedList in reverse sequential order.

From the final element (tail) to the first element (head), the elements are returned in that order.

Syntax

public Iterator descendingIterator()

Return Value − This method gives an iterator across this LinkedList's elements in reverse order.

descendingInterator()

This approach is comparable to the one above, however, in place of using an ArrayList, we'll turn Set right into a LinkedList object. We will iterate the keys in reverse order as shown below, by using the use of the descendingIterator() function of the LinkedList class.

Algorithm

  • Step 1 − Create a new LinkedHashMap object named "lhmap".

  • Step 2 − Add key-value pairs to the "lhmap" LinkedHashMap.

  • Step 3 − Get the set of keys from the "lhmap" LinkedHashMap.

  • Step 4 − Create a new LinkedList "listKeys.” Initialize it with the contents of "setKeys".

  • Step 5 − Generate an iterator. Here we have named it as "iterator" with the help of the descendingIterator() method of the "listKeys" LinkedList.

  • Step 6 − Iterate via the keys in descending order with the usage of a while loop.

  • Step 7 − Inside the loop, retrieve the next key from the iterator and print the corresponding value from the "lhmap" LinkedHashMap.

  • Step 8 − End the loop.

  • Step 9 − End the program.

Example

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;

public class Tutorialspoint {

   public static void main(String[] args) {

      LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<>();

      lhmap.put(10, "Ten");
      lhmap.put(20, "Twenty");
      lhmap.put(30, "Thirty");
      lhmap.put(40, "Forty");
      lhmap.put(50, "Fifty");

      Set<Integer> setKeys = lhmap.keySet();

      LinkedList<Integer> listKeys = new LinkedList<>(setKeys);

      Iterator<Integer> iterator = listKeys.descendingIterator();

      while (iterator.hasNext()) {
         System.out.println(lhmap.get(iterator.next()));
      }
   }
}

Output

Fifty
Forty
Thirty
Twenty
Ten

Conclusion

LinkedHashMap plays a crucial role in maintaining the exact order of element addition and providing a means to access elements in their insertion sequence. It goes beyond the capabilities of the HashMap class by implementing the Map interface and supporting unique element mappings. This allows for the utilization of diverse data types when assigning keys and values. By initially reversing the elements, we have the ability to modify the order within the linked hash map and repeat the process as needed. Three methods, namely listIterator(), reverse(), and descendingIterator(), offer options to iterate over a LinkedHashMap in reverse order.

Updated on: 18-Oct-2023

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements