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
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:" );
LinkedHashMap<Integer, String> lhm
= new LinkedHashMap<Integer, String>();
lhm.put( 1 , "Sravan Kumar" );
lhm.put( 2 , "Ishitha" );
lhm.put( 3 , "Harsha" );
lhm.put( 4 , "Vamsi" );
lhm.put( 5 , "Jyothika" );
System.out.println(
"Insertion Order of LinkedHashMap:"
+ " iterating \n" );
Set<Integer> set = lhm.keySet();
Iterator<Integer> itr = set.iterator();
while (itr.hasNext()) {
Integer key = itr.next();
System.out.println( "Key : " + key + "\t\t"
+ "Value : " + lhm.get(key));
}
System.out.println( "\n\nReverse of Insertion Order:"
+ " iterating \n" );
List<Integer> alKeys
= new ArrayList<Integer>(lhm.keySet());
Collections.reverse(alKeys);
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
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)
{
LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();
System.out.println( "Staff DataBase" );
lhm.put( "CSE" , "Subba Rao" );
lhm.put( "IT" , "Maruti" );
lhm.put( "Civil" , "Sundari Devi" );
System.out.println(
"Insertion Order of LinkedHashMap:"
+ " iterating \n" );
Set<String> set = lhm.keySet();
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
String key = itr.next();
System.out.println( "Key : " + key + "\t\t"
+ "Value : " + lhm.get(key));
}
System.out.println( "\n\nReverse of Insertion Order:"
+ " iterating \n" );
List<String> alKeys
= new ArrayList<String>(lhm.keySet());
Collections.reverse(alKeys);
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
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)
{
LinkedHashMap<String, String> lhmap
= new LinkedHashMap<String, String>();
lhmap.put( "one" , "Geeks" );
lhmap.put( "two" , "For" );
lhmap.put( "three" , "Geeks" );
Set<String> setKeys = lhmap.keySet();
List<String> listKeys
= new ArrayList<String>(setKeys);
ListIterator<String> iterator
= listKeys.listIterator(listKeys.size());
while (iterator.hasPrevious()) {
String key = iterator.previous();
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
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)
{
LinkedHashMap<String, String> lhmap
= new LinkedHashMap<String, String>();
lhmap.put( "one" , "Geeks" );
lhmap.put( "two" , "For" );
lhmap.put( "three" , "Geeks" );
Set<String> setKeys = lhmap.keySet();
LinkedList<String> listKeys
= new LinkedList<String>(setKeys);
Iterator<String> iterator
= listKeys.descendingIterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " " + lhmap.get(key));
}
}
}
|
Output
three 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 List in Reverse Order in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Example Input: ["
3 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 LinkedList in Java?
LinkedList in java is basically a part of the collection framework present in java.util package. It is the implementation of the LinkedList data structure that stores elements in a non-contiguous manner inside the memory. Five ways to iterate a LinkedList are: Using for loopUsing while loopUsing enh
5 min read
How to Check the LinkedHashMap Size in Java?
Size of LinkedHashMap can be obtained in multiple ways like by using an inbuilt function and by iterating through the LinkedHashMap. Example: Input : List : [1 : "John", 2 : "Tom", 3 : "Tim"] Output: 3 Input : List : [1 : "John", 2 : "Tom"] Output: 2Approach 1: using Iteration Create a size variable
2 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
Iterate through LinkedHashMap using an Iterator in Java
LinkedHashMap is a pre-defined class in java like HashMap. The only difference between LinkedHashMap and HashMap is LinkedHashMap preserve insertion order while HashMap does not preserve insertion order. The task is to iterate through a LinkedHashMap using an Iterator. We use the Iterator object to
2 min read