How does LinkedHashMap maintain Insertion Order?
Last Updated :
05 Feb, 2024
LinkedHashMap in Java maintains the order of elements based on which they were inserted. It achieves this by using a doubly-linked list internally to maintain the order of elements along with a hash table for retrieval.
In this article, we are going to discuss how LinkedHashMap maintains insertion order.
Example of LinkedHashMap to maintain insertion order:
Input: LinkedHashMap elements in insertion order:
One: 1
Two: 2
Output: LinkedHashMap elements after adding more elements:
One: 1
Two: 2
Three: 3
Four: 4
Syntax of LinkedHashMap:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
Where,
- K: It is the type of keys maintained.
- V: It is the type of mapped values.
Program to maintain insertion order in LinkedHashMap in Java
Below is the implementation of LinkedHashMap to maintain insertion order.
Java
import java.util.LinkedHashMap;
import java.util.Map;
class GFG{
public static void main(String[] args) {
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put( "One" , 1 );
linkedHashMap.put( "Two" , 2 );
linkedHashMap.put( "Three" , 3 );
System.out.println( "LinkedHashMap elements in insertion order:" );
for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
linkedHashMap.put( "Four" , 4 );
linkedHashMap.put( "Five" , 5 );
System.out.println( "\nLinkedHashMap elements after adding more elements:" );
for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
|
Output
LinkedHashMap elements in insertion order:
One: 1
Two: 2
Three: 3
LinkedHashMap elements after adding more elements:
One: 1
Two: 2
Three: 3
Four: 4
Five: 5
Explanation of the Program:
- In the above Java program, it demonstrates maintaining insertion order in a LinkedHashMap.
- It starts by creating a LinkedHashMap and adding elements to it.
- The program then iterates over the entries, displaying them in the order they were added.
- After adding more elements, it iterates again, showing an insertion order.
- It shows how a LinkedHashMap keeps track of the order in which elements are added.
Share your thoughts in the comments
Please Login to comment...