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));
}
}
}
OutputStudent 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));
}
}
}
OutputStaff 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));
}
}
}
Outputthree 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));
}
}
}
Outputthree Geeks
two For
one Geeks
Similar Reads
Iterate a LinkedList in Reverse Order in Java
For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the
2 min read
How to iterate LinkedHashMap in Java?
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. Th
2 min read
Iterate TreeMap in Reverse Order in Java
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. There are three simple ways to iterate TreeMap in reverse order in Java: Using the reverseOrder() methodUsing the descend
3 min read
How to Merge Two LinkedHashMaps in Java?
In Java, LinkedHashMap is a class that extends HashMap and maintains the order of elements based on the order of insertion. Merging two LinkedHashMaps involves combining their key-value pairs while ensuring that the order is preserved. In, this article we will explore different approaches to merging
3 min read
How to Iterate the Vector Elements in the Reverse Order in Java?
The Vector class is found in java.util package and it implements List interface. The Vector class is included in the java collection framework from Java version 1.2. Unlike arrays, vectors can grow and shrink their size, and thus they are also called the Dynamic Array. Vectors are synchronized, ie t
3 min read
Sort LinkedHashMap by Values using Comparable Interface in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. Assuming you have gone through LinkedHashMap in java and know about LinkedHashMap. Syntax: int compare(T obj) ; Illustration: Input : { GEEKS=1, geeks=3, for=2 } Output : { GEEKS=1
2 min read
Java Program to Iterate LinkedHashSet Elements
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read
How to Check if LinkedHashMap is Empty in Java?
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements
2 min read
How to Iterate Over the Elements in a TreeSet in Natural Order in Java?
In Java, to iterate over the elements of a TreeSet in their Natural Order, one must either use a custom comparator provided or traverse the elements in ascending order based on their natural ordering. A TreeSet in Java keeps up with its components in arranged requests. In this article, we will learn
2 min read
How to Print all Keys of the LinkedHashMap in Java?
LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHas
2 min read