← Back to Chapters

LinkedHashMap

? LinkedHashMap

? Quick Overview

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.

? Key Concepts

  • Maintains insertion order
  • Allows one null key and multiple null values
  • Non-synchronized (not thread-safe)
  • Faster iteration than HashMap
  • Used when predictable iteration order is required

? Interactive Visualizer

Add elements to see how LinkedHashMap links them in the exact order of insertion.

Map is empty

? Syntax & Theory

LinkedHashMap internally uses a doubly-linked list to store entries in sequence. This ensures elements are returned in the same order they were inserted.

? View Code Example
// 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);
}
}

?️ Output Explanation

The output displays elements in the same order they were inserted into the map. Unlike HashMap, order is preserved.

? Tips & Best Practices

  • Use LinkedHashMap when order matters
  • Prefer HashMap if order is not required for better performance
  • Wrap with Collections.synchronizedMap() for thread safety

? Try It Yourself

  • Add duplicate keys and observe behavior
  • Insert a null key and multiple null values
  • Compare output with HashMap