LinkedHashMap, TreeMap, EnumMap

Collections · lesson 8 of 42 · 4 min read

Choose the map that gives you insertion order, sorted keys, or enum-keyed speed.

Open this lesson in the learning hub

Key points

  • LinkedHashMap keeps insertion order. It is the drop-in fix when HashMap output looks scrambled.
  • Third constructor arg true switches it to access order. Override removeEldestEntry for an LRU cache.
  • TreeMap sorts by key and implements NavigableMap: floorEntry, headMap.
  • TreeMap operations are O(log n) and it rejects null keys, because it must compare them.
  • EnumMap is backed by a plain array indexed by ordinal. For enum keys it beats HashMap on both speed and memory.
  • EnumMap always iterates in enum declaration order, whatever order you inserted in.

Example

import java.util.*;

public class Main {
    enum Day { MON, TUE, WED }

    public static void main(String[] args) {
        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        Map<String, Integer> tree = new TreeMap<>();
        for (Map<String, Integer> m : List.of(hash, linked, tree)) {
            m.put("zebra", 1);
            m.put("apple", 2);
            m.put("mango", 3);
        }
        System.out.println("HashMap       : " + hash + "   (no order promised)");
        System.out.println("LinkedHashMap : " + linked + "   (insertion order)");
        System.out.println("TreeMap       : " + tree + "   (sorted by key)");

        TreeMap<Integer, String> grades = new TreeMap<>();
        grades.put(60, "D"); grades.put(70, "C"); grades.put(80, "B"); grades.put(90, "A");
        System.out.println("floorEntry(85): " + grades.floorEntry(85));
        System.out.println("headMap(80)   : " + grades.headMap(80));
        System.out.println("descendingMap : " + grades.descendingMap());

        EnumMap<Day, String> plan = new EnumMap<>(Day.class);
        plan.put(Day.WED, "ship");
        plan.put(Day.MON, "plan");
        System.out.println("EnumMap       : " + plan + "   (enum declaration order)");

        LinkedHashMap<String, Integer> lru = new LinkedHashMap<>(16, 0.75f, true) {
            @Override protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
                return size() > 3;
            }
        };
        for (String k : List.of("a", "b", "c")) lru.put(k, 1);
        lru.get("a");
        lru.put("d", 1);
        System.out.println("LRU keys      : " + lru.keySet() + "   ('b' evicted)");
    }
}

Same Map interface, three different promises about order. Pick the promise you need.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.