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)