Open In App

How does LinkedHashMap maintain Insertion Order?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to maintain insertion order in LinkedHashMap
import java.util.LinkedHashMap;
import java.util.Map;
  
class GFG{
    public static void main(String[] args) {
        // Creating a LinkedHashMap
        Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
  
        // Adding elements
        linkedHashMap.put("One", 1);
        linkedHashMap.put("Two", 2);
        linkedHashMap.put("Three", 3);
  
        // Iterating over the entries
        System.out.println("LinkedHashMap elements in insertion order:");
        for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
  
        // Adding more elements
        linkedHashMap.put("Four", 4);
        linkedHashMap.put("Five", 5);
  
        // Iterating again after adding more elements
        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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads