TreeMap and LinkedHashMap

HashMap, LinkedHashMap and TreeMap hold the same data but loop over it in different orders: unpredictable, insertion or access order, and sorted. That choice also changes cost and what each map can do. This page explains how each keeps its order, shows the ordering rules and the Java 21 sequenced methods, builds an LRU cache, and measures put, get and iteration.

Contents

Three maps, three orders

All three classes implement Map, so code that only puts and gets works with any of them. They differ in the extra structure they maintain:

  • HashMap (Java 1.2) is a hash table. Iteration follows the bucket array, so the order depends on hash codes and table size and can change when the map grows.
  • LinkedHashMap (Java 1.4) is a HashMap whose entries are also linked in a doubly linked list. The list records insertion order, or, if requested, access order, and iteration follows it. Lookups stay as fast as in a HashMap.
  • TreeMap (Java 1.2) is a red-black tree sorted by key, using natural order or a comparator. Iteration is sorted, and it offers nearest-key and range queries, at O(log n) per operation.
HashMap, LinkedHashMap and TreeMap compared
PropertyHashMapLinkedHashMapTreeMap
Iteration orderUnspecifiedInsertion or accessSorted by key
get, putO(1)O(1)O(log n)
Null keysOne allowedOne allowedNot with natural order
Key requirementequals, hashCodeequals, hashCodeComparable or a comparator
Entry object (compressed references)About 32 bytesAbout 40 bytesAbout 40 bytes
SequencedMap (Java 21)NoYesYes (also NavigableMap)
Best forLookupsPredictable order, cachesSorted output, ranges

The entry sizes follow from the fields each entry object holds: a LinkedHashMap entry adds two links to a HashMap node, and a TreeMap entry holds key, value, parent and two child links. All of the programs were run with JDK 21.

The same data in three orders

City populations are inserted in an order that is neither alphabetical nor by size, so each map's order is easy to tell apart. A fourth map sorts by a comparator instead of natural order.

Java
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class ThreeOrders {

    static void fill(Map<String, Integer> map) {
        map.put("zurich", 8);
        map.put("athens", 3);
        map.put("mumbai", 20);
        map.put("berlin", 4);
        map.put("athens", 4);          // update: does not move the key in any of the three
    }

    public static void main(String[] args) {
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        Map<String, Integer> tree = new TreeMap<>();
        fill(hash);
        fill(linked);
        fill(tree);
        System.out.println("HashMap:       " + hash);
        System.out.println("LinkedHashMap: " + linked);
        System.out.println("TreeMap:       " + tree);

        // TreeMap with a comparator: longest name first, then alphabetical
        Map<String, Integer> byLength = new TreeMap<>(
                Comparator.comparing(String::length).reversed()
                        .thenComparing(Comparator.naturalOrder()));
        byLength.putAll(tree);
        byLength.put("rome", 3);
        System.out.println("TreeMap(cmp):  " + byLength);
    }
}

Output:

Output
HashMap:       {mumbai=20, zurich=8, athens=4, berlin=4}
LinkedHashMap: {zurich=8, athens=4, mumbai=20, berlin=4}
TreeMap:       {athens=4, berlin=4, mumbai=20, zurich=8}
TreeMap(cmp):  {athens=4, berlin=4, mumbai=20, zurich=8, rome=3}
  • The HashMap printed mumbai first, an order that comes from the hash codes.
  • The LinkedHashMap kept insertion order: zurich, athens, mumbai, berlin.
  • The TreeMap sorted the keys alphabetically.
  • The comparator comparing(String::length).reversed().thenComparing(naturalOrder()) sorted longest names first, with alphabetical order breaking ties, so the added rome came last. A comparator without the tie-breaker would treat athens and berlin, both six letters, as the same key.

Ordering rules worth knowing

A few rules decide where a key ends up, and they are easy to get wrong. Each line of the program tests one.

Java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class InsertionOrderRules {

    public static void main(String[] args) {
        // Re-putting an existing key does NOT move it in insertion order
        LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
        m.put("a", 1);
        m.put("b", 2);
        m.put("c", 3);
        m.put("a", 10);
        System.out.println("put(a) again:         " + m);
        m.remove("a");
        m.put("a", 11);
        System.out.println("remove then put(a):   " + m);

        // Java 21: putFirst / putLast move a key to an end
        m.putFirst("c", 30);
        System.out.println("putFirst(c):          " + m);
        m.putLast("b", 20);
        System.out.println("putLast(b):           " + m);

        // Access order: get() moves the key to the end
        LinkedHashMap<String, Integer> access = new LinkedHashMap<>(16, 0.75f, true);
        access.putAll(Map.of("x", 1));
        access.put("y", 2);
        access.put("z", 3);
        access.get("x");
        access.getOrDefault("y", 0);
        System.out.println("access order after get(x), getOrDefault(y): " + access.keySet());

        // TreeMap with a comparator that treats different keys as equal merges them
        TreeMap<String, Integer> ci = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        ci.put("Apple", 1);
        ci.put("APPLE", 2);
        System.out.println("case-insensitive TreeMap: " + ci + " (first key kept, value replaced)");

        // TreeMap rejects null keys; HashMap and LinkedHashMap accept one
        try {
            new TreeMap<String, Integer>().put(null, 1);
        } catch (NullPointerException e) {
            System.out.println("TreeMap.put(null, ...): NullPointerException");
        }
        LinkedHashMap<String, Integer> withNull = new LinkedHashMap<>();
        withNull.put(null, 0);
        System.out.println("LinkedHashMap with a null key: " + withNull);
    }
}

Output:

Output
put(a) again:         {a=10, b=2, c=3}
remove then put(a):   {b=2, c=3, a=11}
putFirst(c):          {c=30, b=2, a=11}
putLast(b):           {c=30, a=11, b=20}
access order after get(x), getOrDefault(y): [z, x, y]
case-insensitive TreeMap: {Apple=2} (first key kept, value replaced)
TreeMap.put(null, ...): NullPointerException
LinkedHashMap with a null key: {null=0}
  • Putting an existing key again replaces the value but keeps the key's original position: a stayed first. Removing and re-adding moves it to the end.
  • Java 21 added putFirst and putLast to LinkedHashMap, which insert or move a key to one end.
  • In access order, both get and getOrDefault count as access and move the key to the end, leaving z, the least recently used, at the front.
  • A TreeMap uses its comparator, not equals, to decide whether keys are the same. With CASE_INSENSITIVE_ORDER, APPLE replaced the value of Apple, and the first spelling stayed as the key.
  • A TreeMap with natural order rejects a null key, because it cannot compare it. HashMap and LinkedHashMap accept one.

Sequenced methods (Java 21)

Java 21 (JEP 431) made LinkedHashMap and TreeMap implement SequencedMap, with methods for both ends and a reversed view. A checkout funnel in insertion order and a sorted ranking show them.

Java
import java.util.LinkedHashMap;
import java.util.SequencedMap;
import java.util.TreeMap;

public class SequencedViews {

    public static void main(String[] args) {
        // Java 21: both classes implement SequencedMap
        SequencedMap<String, Integer> steps = new LinkedHashMap<>();
        steps.put("checkout", 2);
        steps.put("cart", 1);
        steps.putFirst("browse", 0);          // insert at the front
        steps.putLast("confirm", 3);
        System.out.println("steps:      " + steps);
        System.out.println("first:      " + steps.firstEntry() + ", last: " + steps.lastEntry());
        System.out.println("reversed:   " + steps.reversed());

        SequencedMap<Integer, String> ranks = new TreeMap<>();
        ranks.put(3, "bronze");
        ranks.put(1, "gold");
        ranks.put(2, "silver");
        System.out.println("pollFirst:  " + ranks.pollFirstEntry() + ", left " + ranks);
    }
}

Output:

Output
steps:      {browse=0, checkout=2, cart=1, confirm=3}
first:      browse=0, last: confirm=3
reversed:   {confirm=3, cart=1, checkout=2, browse=0}
pollFirst:  1=gold, left {2=silver, 3=bronze}
  • firstEntry() and lastEntry() read the ends of a LinkedHashMap without iterating; before Java 21 this needed an iterator or a loop to the end.
  • reversed() returns a view in reverse order, without copying.
  • pollFirstEntry() removes and returns the first entry, here the gold ranking from a TreeMap.

An LRU cache in a few lines

An access-ordered LinkedHashMap with an overridden removeEldestEntry is a complete least-recently-used cache. The program fills a cache of three, reads one entry, and adds a fourth.

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class LruCache {

    // accessOrder = true: every get or put moves the entry to the end.
    // removeEldestEntry is asked after each put whether to drop the first entry.
    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("a", "page A");
        cache.put("b", "page B");
        cache.put("c", "page C");
        System.out.println("full:          " + cache.keySet());

        cache.get("a");                               // a is now the most recently used
        System.out.println("after get(a):  " + cache.keySet());

        cache.put("d", "page D");                     // over capacity: evicts b, the least recent
        System.out.println("after put(d):  " + cache.keySet());
        System.out.println("b still cached? " + cache.containsKey("b"));
    }
}

Output:

Output
full:          [a, b, c]
after get(a):  [b, c, a]
after put(d):  [c, a, d]
b still cached? false
  • Reading a moved it to the most-recent end, so when d arrived, b was the eldest entry and was evicted.
  • removeEldestEntry is called after every insertion; returning true removes the first entry in the linked order.
  • The class is not thread-safe. Wrap it with Collections.synchronizedMap, or use a caching library such as Caffeine for concurrent caches with expiry.

What the order costs

The program puts, gets and iterates 500,000 random integer keys in each map, keeping the fastest of three runs for each operation.

Java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.function.Supplier;

public class MapCost {

    public static void main(String[] args) {
        int n = 500000;
        int[] keys = new Random(3).ints(n, 0, Integer.MAX_VALUE).toArray();
        System.out.printf("%-14s %10s %10s %12s%n", "", "put (ms)", "get (ms)", "iterate (ms)");
        row("HashMap", HashMap::new, keys);
        row("LinkedHashMap", LinkedHashMap::new, keys);
        row("TreeMap", TreeMap::new, keys);
    }

    static void row(String name, Supplier<Map<Integer, Integer>> factory, int[] keys) {
        double put = Double.MAX_VALUE;
        double get = Double.MAX_VALUE;
        double iter = Double.MAX_VALUE;
        Map<Integer, Integer> m = null;
        for (int run = 0; run < 3; run++) {
            m = factory.get();
            long t0 = System.nanoTime();
            for (int k : keys) {
                m.put(k, k);
            }
            put = Math.min(put, (System.nanoTime() - t0) / 1e6);
            t0 = System.nanoTime();
            long s = 0;
            for (int k : keys) {
                s += m.get(k);
            }
            get = Math.min(get, (System.nanoTime() - t0) / 1e6);
            t0 = System.nanoTime();
            for (Map.Entry<Integer, Integer> e : m.entrySet()) {
                s += e.getValue();
            }
            iter = Math.min(iter, (System.nanoTime() - t0) / 1e6);
            if (s == 42) {
                System.out.println();
            }
        }
        System.out.printf("%-14s %10.1f %10.1f %12.1f%n", name, put, get, iter);
    }
}

Output (rough numbers from a 2-CPU Linux machine with JDK 21):

Output
put (ms)   get (ms) iterate (ms)
HashMap              91.2       18.9          8.2
LinkedHashMap        63.7       13.1          5.8
TreeMap             383.5      306.3         47.6
  • Filling the LinkedHashMap took anything from a little less time than the HashMap to more than twice as long across runs, so the shared machine's noise is as large as the difference here. Each new entry is bigger and must be linked in, so on a quiet machine expect it to be somewhat slower. Its get was no slower than the HashMap one in any run. Keeping insertion order costs memory and insertion time, not lookup time.
  • TreeMap was several times slower for put and often more than ten times slower for get: each operation walks about 19 levels of the tree and compares keys at every step.
  • Iteration was fast for all three. LinkedHashMap iterates its linked list rather than the bucket array, which also makes its iteration time independent of the table capacity.

Copying and collecting without losing the order

A map's order lives in the map object, not in the data. Every time entries move into a new map, through a constructor, putAll or a collector, the new map imposes its own order. The program shows where that silently discards an order you meant to keep.

Java
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class CopyingOrder {

    public static void main(String[] args) {
        List<String> words = List.of("pear", "Fig", "apple", "kiwi", "Banana", "plum");

        // 1. A sorted stream collected with toMap loses its order
        Map<String, Integer> plain = words.stream().sorted()
            .collect(Collectors.toMap(w -> w, String::length));
        Map<String, Integer> kept = words.stream().sorted()
            .collect(Collectors.toMap(w -> w, String::length, (a, b) -> a, LinkedHashMap::new));
        System.out.println("sorted, toMap:                " + plain.keySet() + " "
            + plain.getClass().getSimpleName());
        System.out.println("sorted, toMap(LinkedHashMap): " + kept.keySet());

        // 2. Copying a HashMap into a LinkedHashMap freezes the hash order, it does not sort
        Map<String, Integer> hash = new HashMap<>(kept);
        System.out.println("new LinkedHashMap<>(hashMap): " + new LinkedHashMap<>(hash).keySet());
        System.out.println("new TreeMap<>(hashMap):       " + new TreeMap<>(hash).keySet());

        // 3. The comparator survives a copy only if the static type is SortedMap
        TreeMap<String, Integer> ci = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        ci.putAll(kept);
        Map<String, Integer> asMap = ci;
        TreeMap<String, Integer> copyA = new TreeMap<>(ci);      // TreeMap(SortedMap)
        TreeMap<String, Integer> copyB = new TreeMap<>(asMap);   // TreeMap(Map)
        System.out.println("case-insensitive original: " + ci.keySet());
        System.out.println("copy from a TreeMap variable: " + copyA.keySet()
            + ", comparator kept: " + (copyA.comparator() != null));
        System.out.println("copy from a Map variable:     " + copyB.keySet()
            + ", comparator kept: " + (copyB.comparator() != null));

        // 4. Map equality ignores order entirely
        Map<String, Integer> reversed = new TreeMap<>(Comparator.reverseOrder());
        reversed.putAll(kept);
        System.out.println("TreeMap(reverse).equals(LinkedHashMap): " + reversed.equals(kept)
            + ", same toString: " + reversed.toString().equals(kept.toString()));

        // 5. Sorting a LinkedHashMap by value means building a new one
        Map<String, Integer> byLength = kept.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue()
                .thenComparing(Map.Entry.comparingByKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (a, b) -> a, LinkedHashMap::new));
        System.out.println("by value, then key: " + byLength);
    }
}
Output
sorted, toMap:                [plum, apple, kiwi, pear, Fig, Banana] HashMap
sorted, toMap(LinkedHashMap): [Banana, Fig, apple, kiwi, pear, plum]
new LinkedHashMap<>(hashMap): [plum, apple, kiwi, pear, Fig, Banana]
new TreeMap<>(hashMap):       [Banana, Fig, apple, kiwi, pear, plum]
case-insensitive original: [apple, Banana, Fig, kiwi, pear, plum]
copy from a TreeMap variable: [apple, Banana, Fig, kiwi, pear, plum], comparator kept: true
copy from a Map variable:     [Banana, Fig, apple, kiwi, pear, plum], comparator kept: false
TreeMap(reverse).equals(LinkedHashMap): true, same toString: false
by value, then key: {Fig=3, kiwi=4, pear=4, plum=4, apple=5, Banana=6}
  • A sorted stream collected with plain toMap came out as [plum, apple, kiwi, pear, Fig, Banana] in a HashMap. The four-argument toMap with LinkedHashMap::new kept the sorted order, with the capitalised words first because uppercase letters sort before lowercase.
  • Copying the HashMap into a LinkedHashMap kept the hash order it was given, because that was the order in which the entries arrived. To sort, copy into a TreeMap.
  • The copy made from a variable of type TreeMap kept the case-insensitive comparator, while the copy of the same object through a Map variable lost it and sorted Banana and Fig first. Java picks the constructor from the variable's declared type: TreeMap(SortedMap) keeps the ordering, and TreeMap(Map) is documented to use natural ordering.
  • A TreeMap in reverse order equalled the LinkedHashMap, although their toString output differed. Map.equals compares only the mappings, so a test that checks order must compare key lists, for example new ArrayList<>(map.keySet()).
  • No map keeps entries sorted by value. Streaming the entries, sorting with comparingByValue().thenComparing(comparingByKey()) and collecting into a LinkedHashMap gave a snapshot ordered by word length, with ties in key order. The snapshot does not re-sort when values change later.

Measuring the memory per entry

The comparison table near the top of this page gives estimated entry sizes. This program checks them by filling each map with one million entries and measuring how much the heap grew. The keys and values are created once beforehand and shared, so the figure covers only the map's own objects.

Java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Supplier;

public class MapMemory {

    static final int N = 1000000;
    static Integer[] keys = new Integer[N];

    public static void main(String[] args) {
        for (int i = 0; i < N; i++) {
            keys[i] = i;                       // keys are shared, so only map overhead is counted
        }
        System.out.printf("heap retained per entry, %,d entries (smallest of 3 measurements):%n",
            N);
        measure("HashMap", HashMap::new);
        measure("LinkedHashMap", LinkedHashMap::new);
        measure("TreeMap", TreeMap::new);
    }

    static void measure(String name, Supplier<Map<Integer, Integer>> factory) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long before = used();
            Map<Integer, Integer> map = factory.get();
            for (Integer k : keys) {
                map.put(k, k);
            }
            long after = used();
            best = Math.min(best, after - before);
            if (map.size() != N) {
                throw new AssertionError();
            }
        }
        System.out.printf("  %-14s %5.1f bytes%n", name, (double) best / N);
    }

    static long used() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return rt.totalMemory() - rt.freeMemory();
    }
}

Output (2-CPU Linux machine, JDK 21, default settings with compressed references; heap measurements after System.gc() are approximate):

Output
heap retained per entry, 1,000,000 entries (smallest of 3 measurements):
  HashMap         41.5 bytes
  LinkedHashMap   49.5 bytes
  TreeMap         40.0 bytes
  • TreeMap needed about 40 bytes per entry, matching one tree entry object with its key, value, three links and colour flag. It has no array, so nothing else is allocated.
  • HashMap needed about 41 bytes: a 32-byte node plus its share of the bucket array. One million entries grow the table to 2,097,152 slots of 4 bytes each, which adds a little over 8 bytes per entry.
  • LinkedHashMap needed about 49 to 50 bytes, the same array share plus a 40-byte entry with its before and after links. Keeping insertion order costs about a fifth more memory than a HashMap.

Boxed keys and values usually cost more than the map itself: each Integer outside the small cached range takes 16 bytes. For large maps of numbers, a primitive collection library or an array indexed by key saves far more than choosing between these three classes. Run the same measurement on your own key and value types before deciding that a map is too big.

Which map to use

Choosing between the three maps
You needUse
Fast lookups, order does not matterHashMap
Iteration in insertion orderLinkedHashMap
Least recently used first, evictionLinkedHashMap with access order and removeEldestEntry
Sorted keys or custom key orderTreeMap
Nearest key, ranges, first and last by keyTreeMap; see NavigableMap
Ends and reversed view, insertion orderLinkedHashMap with Java 21 sequenced methods
Sorted and concurrentConcurrentSkipListMap
Enum keysEnumMap; see EnumMap

How the hash table underneath HashMap and LinkedHashMap works is described on HashMap internals.