00:00

Difference Between HashMap and LinkedHashMap in Java

HashMap and LinkedHashMap store key–value pairs with O(1) average operations, unique keys, one null key and any number of null values. LinkedHashMap extends HashMap and adds a doubly linked list through its entries, which gives it a predictable iteration order:

  • HashMap: no ordering guarantee.
  • LinkedHashMap: insertion order by default, or access order (least recently used first), which makes it ideal for LRU caches.

1. Comparison Table

AspectHashMapLinkedHashMap
Iteration orderUnpredictableInsertion order, or access order if configured
Internal structureHash table (buckets)Hash table + doubly linked list of entries
HierarchyExtends AbstractMapExtends HashMap; implements SequencedMap (Java 21)
get / put / removeO(1) averageO(1) average, slightly more work
Iteration costProportional to capacity + sizeProportional to size
MemoryLowerHigher (before/after references per entry)
Eviction hookNoremoveEldestEntry()
NullsOne null key, null valuesOne null key, null values
Thread-safeNoNo

2. Insertion Order

MapOrder.java
import java.util.*;

public class MapOrder {
    public static void main(String[] args) {
        String[] cities = {"Pune", "Delhi", "Kochi", "Agra", "Mumbai"};
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        for (int i = 0; i < cities.length; i++) { hash.put(cities[i], i + 1); linked.put(cities[i], i + 1); }

        System.out.println("HashMap       : " + hash + "  <- no guaranteed order");
        System.out.println("LinkedHashMap : " + linked + "  <- insertion order");

        linked.put("Delhi", 99);                 // updating a key keeps its position
        System.out.println("update Delhi  : " + linked);

        // Java 21 SequencedMap methods
        LinkedHashMap<String, Integer> seq = new LinkedHashMap<>(linked);
        System.out.println("firstEntry    : " + seq.firstEntry() + ", lastEntry: " + seq.lastEntry());
        seq.putFirst("Goa", 0);
        System.out.println("putFirst(Goa) : " + seq.sequencedKeySet());
    }
}
Output
HashMap       : {Delhi=2, Kochi=3, Pune=1, Agra=4, Mumbai=5}  <- no guaranteed order
LinkedHashMap : {Pune=1, Delhi=2, Kochi=3, Agra=4, Mumbai=5}  <- insertion order
update Delhi  : {Pune=1, Delhi=99, Kochi=3, Agra=4, Mumbai=5}
firstEntry    : Pune=1, lastEntry: Mumbai=5
putFirst(Goa) : [Goa, Pune, Delhi, Kochi, Agra, Mumbai]

Updating an existing key does not move it. Java 21 adds firstEntry, lastEntry, putFirst, putLast, pollFirstEntry and reversed.

3. Access Order and LRU Caches

With the constructor LinkedHashMap(capacity, loadFactor, true), every get or put moves the entry to the end. Overriding removeEldestEntry then evicts the least recently used entry automatically:

LruCache.java
import java.util.*;

public class LruCache {
    // accessOrder = true + removeEldestEntry -> a tiny LRU cache
    static class Lru<K, V> extends LinkedHashMap<K, V> {
        private final int capacity;
        Lru(int capacity) { super(16, 0.75f, true); this.capacity = capacity; }
        @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; }
    }

    public static void main(String[] args) {
        Lru<String, String> cache = new Lru<>(3);
        cache.put("u1", "Asha"); cache.put("u2", "Ravi"); cache.put("u3", "Meera");
        System.out.println("initial      : " + cache.keySet());
        cache.get("u1");                         // access moves u1 to the end (most recent)
        System.out.println("after get u1 : " + cache.keySet());
        cache.put("u4", "Kiran");                // evicts least recently used: u2
        System.out.println("after put u4 : " + cache.keySet());
    }
}
Output
initial      : [u1, u2, u3]
after get u1 : [u2, u3, u1]
after put u4 : [u3, u1, u4]

This is enough for simple single-threaded caches; for concurrent production caches, use a library such as Caffeine.

4. When to Use Which

  • HashMap: the default when order does not matter.
  • LinkedHashMap: when output order must match insertion (JSON-like data, reports, configuration), or for LRU caches.
  • TreeMap: when keys must be sorted. See HashMap vs TreeMap.

5. Summary

  • Both offer O(1) average map operations and allow one null key.
  • HashMap has no defined order; LinkedHashMap keeps insertion or access order.
  • LinkedHashMap uses a little more memory and supports eviction with removeEldestEntry.
  • Neither is thread-safe.

Related Tutorials