LinkedHashMap is a special implementation of the Map interface in Java that maintains the insertion order of elements. It combines the features of HashMap and LinkedList.
Add elements to see how LinkedHashMap links them in the exact order of insertion.
Map is empty
LinkedHashMap internally uses a doubly-linked list to store entries in sequence. This ensures elements are returned in the same order they were inserted.
// Import LinkedHashMap class
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
// Create LinkedHashMap object
LinkedHashMap map = new LinkedHashMap<>();
// Add key-value pairs
map.put(101, "Java");
map.put(102, "Python");
map.put(103, "C++");
// Print LinkedHashMap
System.out.println(map);
}
}
The output displays elements in the same order they were inserted into the map. Unlike HashMap, order is preserved.
LinkedHashMap when order mattersHashMap if order is not required for better performanceCollections.synchronizedMap() for thread safety