Back to The Haunt
The craft3 min read

HashMap for speed, TreeMap for order.

HashMap finds a key by its hash, so get, put and containsKey take O(1) time on average, and its keys come back in no promised order. TreeMap is a red-black tree. Every operation takes O(log n), but its keys stay sorted, and it can find the nearest key to a value. LinkedHashMap sits between them: hash speed, with keys in insertion order.

The same words in three maps

import java.util.*;
public class Maps {
    public static void main(String[] args) {
        String[] words = {"pear", "fig", "apple", "kiwi", "banana"};
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        TreeMap<String, Integer> tree = new TreeMap<>();
        for (String w : words) {
            hash.put(w, w.length());
            linked.put(w, w.length());
            tree.put(w, w.length());
        }
        System.out.println("HashMap:       " + hash);
        System.out.println("LinkedHashMap: " + linked);
        System.out.println("TreeMap:       " + tree);
        TreeMap<Integer, String> slots = new TreeMap<>(Map.of(900, "standup", 1100, "review", 1500, "demo"));
        System.out.println(slots.floorKey(1200) + " " + slots.ceilingKey(1200) + " " + slots.higherKey(1500));
        System.out.println(slots.firstEntry() + " " + slots.headMap(1500));
    }
}

Run it with java Maps.java. On Java 25 it prints:

HashMap:       {banana=6, apple=5, pear=4, kiwi=4, fig=3}
LinkedHashMap: {pear=4, fig=3, apple=5, kiwi=4, banana=6}
TreeMap:       {apple=5, banana=6, fig=3, kiwi=4, pear=4}
1100 1500 null
900=standup {900=standup, 1100=review}

The HashMap order is whatever the hash buckets give, and it can change as the map grows. Never write code or tests that depend on it.

Which to use

  • Counting, grouping, lookups, two-sum style problems: HashMap. It is the default.
  • Keys in sorted order, or the smallest and largest key: TreeMap, with firstKey and lastKey.
  • The nearest key, such as the latest booking at or before 12:00: TreeMap, with floorKey, ceilingKey and higherKey, or the Entry versions that return the value too.
  • A range of keys: TreeMap, with headMap, tailMap and subMap.
  • Insertion order, or an LRU cache: LinkedHashMap.

Traps in each

  • A `HashMap` key needs `equals` and `hashCode` that agree. Change a field they use after inserting, and the key is lost in the wrong bucket. Records give you both methods for free.
  • A `TreeMap` treats `compare(a, b) == 0` as the same key. Order strings by length alone, and putting "bb" silently overwrites the value stored under "aa". Add a tie-breaker with thenComparing.
  • `floorKey` returns `null` when nothing qualifies. Assign that to an int and Java throws NullPointerException. Keep it in an Integer and test it.
  • `null` keys: HashMap allows one; a naturally ordered TreeMap throws.

Chapters 8 and 9 of our free Java for DSA book build a hash table and a binary search tree by hand, then show what HashMap and TreeMap do for you. The DSA hub has the same chapters in four more languages.

That’s it. Come back soon; the ghost keeps writing.Follow by RSS

Read next.