StackTips

LinkedHashMap in Java

siteadmin avtar

Written by:

Stacktips,  2 min read,  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 Spring Boot: A Beginner's Guide

This course covers the fundamentals of Spring Boot an you will gain the necessary skills to develop various types of applications using the powerful features of the Spring Boot framework.

>> CHECK OUT THE COURSE

Continue reading..