StackTips

LinkedHashMap in Java

siteadmin avtar

Written by

Stacktips,  2 min read,  324 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 Python - Beginners Guide

Python is a language with a simple syntax and a powerful set of libraries. It is an interpreted language, with a rich programming environment, including a robust debugger and profiler.

>> CHECK OUT THE COURSE

Continue reading..