StackTips

LinkedHashMap in Java

siteadmin avtar

Written by

Stacktips,  2 min read,  280 views, updated on July 24, 2024

The LinkedHashMap works very similar to HashMap but it maintains a doubly-linked list to maintain the insertion order of elements.

Key Properties of LinkedHashMap

Due to the additional overhead for maintaining order, LinkedHashMap is generally slower as compared to HashMap.

Map<String, Integer> map = new LinkedHashMap<>();  
map.put("B", 2);  
map.put("A", 1);  
map.put("C", 3);  
map.put(null, 4);  

for (Map.Entry<String, Integer> entry : map.entrySet()) {  
    System.out.println(entry.getKey() + ": " + entry.getValue());  
}

Outputs:

Output:
B: 2
A: 1
C: 3
null: 4

Generally, LinkedHashMap maintains the insertion order, but we can change that to access order bypassing the accessOrder true during the constructor initialisation.

Map<String, Integer> map = new LinkedHashMap<>(16, 0.75f, true);  
map.put("B", 2);  
map.put("A", 1);  
map.put("C", 3);  
map.put(null, 4);  

map.get("A");  
map.get("B");  

for (Map.Entry<String, Integer> entry : map.entrySet()) {  
    System.out.println(entry.getKey() + ": " + entry.getValue());  
}

Outputs

Output:
C: 3
null: 4
A: 1
B: 2

Getting Started with Maven - Beginner's Guide

A no-nonsense guide to learn Maven concepts for Java developers. Maven fundamentals crash course for beginners. This Maven fundamentals course is designed to help developers learn Maven, a powerful build automation tool to build, test, and deploy Java applications.

>> CHECK OUT THE COURSE

Continue reading..