DEV Community

Sudhakar V
Sudhakar V

Posted on

LinkedHashMap in Java

πŸ”„ LinkedHashMap in Java

A LinkedHashMap is a HashMap that maintains the insertion order (or access order if configured). It is part of the java.util package and combines hash table and linked list features.


πŸ“Œ Key Features

Feature Description
Maintains Order Keeps the insertion order (or access order)
Allows null keys/values βœ… Yes (only one null key, multiple null values)
Thread-safe ❌ No (use Collections.synchronizedMap() for safety)
Performance Slightly slower than HashMap due to order maintenance
Internal Structure Hash table + doubly linked list

βœ… Syntax

import java.util.LinkedHashMap;

LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
Enter fullscreen mode Exit fullscreen mode

🧠 How It Works

  • Uses a hash table for storage.
  • Uses a doubly linked list to maintain order.
  • Each entry maintains a before and after reference.

πŸ” Constructors

LinkedHashMap()                         // Default constructor
LinkedHashMap(int initialCapacity)      // Set initial size
LinkedHashMap(int initialCapacity, float loadFactor)
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Enter fullscreen mode Exit fullscreen mode
  • accessOrder = false: Keeps insertion order (default)
  • accessOrder = true: Reorders entries on access (used in LRU cache)

πŸ“„ Example: Insertion Order

import java.util.LinkedHashMap;

public class Example {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

        map.put(3, "Three");
        map.put(1, "One");
        map.put(2, "Two");

        System.out.println(map); // Output: {3=Three, 1=One, 2=Two}
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ•ΉοΈ Example: Access Order (LRU Cache)

LinkedHashMap<Integer, String> lruCache = new LinkedHashMap<>(16, 0.75f, true);

lruCache.put(1, "One");
lruCache.put(2, "Two");
lruCache.get(1);  // Accesses key 1

System.out.println(lruCache); // Output: {2=Two, 1=One}
Enter fullscreen mode Exit fullscreen mode

🚨 Removing Eldest Entry (e.g., LRU Cache)

LinkedHashMap<Integer, String> cache = new LinkedHashMap<>(16, 0.75f, true) {
    protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
        return size() > 3; // Keep max 3 items
    }
};
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Comparison with HashMap and TreeMap

Feature HashMap LinkedHashMap TreeMap
Order Maintained ❌ No βœ… Yes (Insertion/Access) βœ… Yes (Sorted)
Performance ⚑ Fast ⚑ Slightly slower 🐒 Slower (sorted)
Underlying Structure Hash Table Hash Table + Linked List Red-Black Tree

βœ… When to Use LinkedHashMap

  • You need a Map with predictable insertion order
  • You want to implement LRU caching
  • You want fast access but also ordered output

Top comments (0)