Skip to content
Related Articles

Related Articles

How to Iterate LinkedHashMap in Reverse Order in Java?
  • Last Updated : 17 Dec, 2020

The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or mappings.

Syntax of Linkedhashmap

public class LinkedHashMap<K,​V> extends HashMap<K,​V> implements Map<K,​V>

Where K is key and V is value.

We can give key and value as our own data types like string, float, integer, etc. We can reverse the elements in the linked hash map by first reversing the elements. After reversing, we can iterate it.

Method 1: ( Using reverse() method)



This method is used to reverse the elements or mappings order in the LinkedHashMap.

Syntax:

public static void reverse(List myList)

Parameters: myList is the List provided to the Collections.reverse(myList) method.

Returns: It does not return anything but modifies the list internally.

Exception: It throws UnsupportedOperationException if the specified List or its list-iterator does not support the set operation.

Steps:

  • Import necessary packages
  • Create a LinkedHashMap with keys and values
  • Reverse the LinkedHashMap
  • Iterate it.

Example 1:

Student details displaying ascending and descending order with an integer as key and value as a string.



Java




// 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 Main {
  
    public static void main(String[] args)
    {
        System.out.println("Student Details:");
        
        // creating HashMap object of type <String, String>
        LinkedHashMap<Integer, String> lhm
            = new LinkedHashMap<Integer, String>();
  
        // adding key-value pairs to HashMap object
        lhm.put(1, "Sravan Kumar");
        lhm.put(2, "Ishitha");
        lhm.put(3, "Harsha");
        lhm.put(4, "Vamsi");
        lhm.put(5, "Jyothika");
  
        // Insertion Order iterating
        System.out.println(
            "Insertion Order of LinkedHashMap:"
            + " 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\nReverse of Insertion Order:"
                           + " 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
Student Details:
Insertion Order of LinkedHashMap: iterating 

Key : 1        Value : Sravan Kumar
Key : 2        Value : Ishitha
Key : 3        Value : Harsha
Key : 4        Value : Vamsi
Key : 5        Value : Jyothika


Reverse of Insertion Order: iterating 

Key : 5        Value : Jyothika
Key : 4        Value : Vamsi
Key : 3        Value : Harsha
Key : 2        Value : Ishitha
Key : 1        Value : Sravan Kumar

Example 2: Both keys and values are of string types.

Java




// 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 Main {
  
    public static void main(String[] args)
    {
  
        // creating HashMap object of type <String, String>
        LinkedHashMap<String, String> lhm
            = new LinkedHashMap<String, String>();
  
        System.out.println("Staff DataBase");
  
        // adding key-value pairs to HashMap object
        lhm.put("CSE", "Subba Rao");
        lhm.put("IT", "Maruti");
        lhm.put("Civil", "Sundari Devi");
  
        // Insertion Order iterating
        System.out.println(
            "Insertion Order of LinkedHashMap:"
            + " iterating \n");
  
        // getting keySet() into Set
        Set<String> set = lhm.keySet();
  
        // get Iterator from key set
        Iterator<String> itr = set.iterator();
  
        // iterating as per Insertion Order
        while (itr.hasNext()) {
            String key = itr.next();
            System.out.println("Key : " + key + "\t\t"
                               + "Value : " + lhm.get(key));
        }
  
        // Reverse of Insertion Order iterating
        System.out.println("\n\nReverse of Insertion Order:"
                           + " iterating \n");
  
        // convert to ArrayList of key set
        List<String> alKeys
            = new ArrayList<String>(lhm.keySet());
  
        // reverse order of keys
        Collections.reverse(alKeys);
  
        // iterate LHM using reverse order of keys
        for (String strKey : alKeys) {
            System.out.println("Key : " + strKey + "\t\t"
                               + "Value : "
                               + lhm.get(strKey));
        }
    }
}
Output
Staff DataBase
Insertion Order of LinkedHashMap: iterating 

Key : CSE        Value : Subba Rao
Key : IT        Value : Maruti
Key : Civil        Value : Sundari Devi


Reverse of Insertion Order: iterating 

Key : Civil        Value : Sundari Devi
Key : IT        Value : Maruti
Key : CSE        Value : Subba Rao

Method 2: (Using the listIterator method)

Syntax:

ListIterator listIterator(int index)

Parameters: This method has only an argument, i.e, index – index of the first element to be returned from the list iterator (by a call to next).

Returns: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

Java




// Java program to iterate 
// LinkedHashMap in reverse order
  
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
  
public class LinkedHashMapIterateReverseExample {
  
    public static void main(String[] args)
    {
  
        // create an instance of linked hashmap
        LinkedHashMap<String, String> lhmap
            = new LinkedHashMap<String, String>();
  
        // Add mappings
        lhmap.put("one", "Geeks");
        lhmap.put("two", "For");
        lhmap.put("three", "Geeks");
  
        // get all keys from the LinkedHashMap
        Set<String> setKeys = lhmap.keySet();
  
        // convert set to list
        List<String> listKeys
            = new ArrayList<String>(setKeys);
  
        // get a ListIterator for the ArrayList and
        // position it at the end to iterate backwards
        ListIterator<String> iterator
            = listKeys.listIterator(listKeys.size());
  
        // Iterate in reverse order using the hasPrevious
        // and previous methods
        while (iterator.hasPrevious()) {
  
            String key = iterator.previous();
  
            // get value mapped to the key
            System.out.println(key + " " + lhmap.get(key));
        }
    }
}
Output
three Geeks
two For
one Geeks

Method 3: (Using the descendingIterator method)

Syntax:

public Iterator descendingIterator()

Return Value: This method returns an iterator over the elements in this LinkedList in reverse sequence.

Java




// Java program to iterate 
// LinkedHashMap in reverse order
  
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Set;
  
public class LinkedHashMapIterateReverseExample {
  
    public static void main(String[] args)
    {
  
        // create an instance of linked hashmap
        LinkedHashMap<String, String> lhmap
            = new LinkedHashMap<String, String>();
  
        // Add mappings
        lhmap.put("one", "Geeks");
        lhmap.put("two", "For");
        lhmap.put("three", "Geeks");
  
        // get all keys from the LinkedHashMap
        Set<String> setKeys = lhmap.keySet();
  
        // convert set to LinkedList
        LinkedList<String> listKeys
            = new LinkedList<String>(setKeys);
  
        // get descending iterator
        Iterator<String> iterator
            = listKeys.descendingIterator();
  
        // iterate the keys and get the values from the
        // map
        while (iterator.hasNext()) {
  
            String key = iterator.next();
  
            // get the value
            System.out.println(key + " " + lhmap.get(key));
        }
    }
}
Output
three Geeks
two For
one Geeks

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :