Core Java · 6. Collections, lesson 5 of 27

Every Map: HashMap, LinkedHashMap, TreeMap, Hashtable and ConcurrentHashMap

Intermediate3 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Choosing a map:

  • HashMap: fastest, no order. The default.
  • LinkedHashMap: keeps insertion order, or access order for caches.
  • TreeMap: sorted by key, with range queries like floorKey, ceilingEntry and headMap.
  • ConcurrentHashMap: safe for many threads.
  • Map.of(…): small, fixed and unmodifiable.

Modern methods that remove boilerplate:

  • getOrDefault(key, fallback)
  • computeIfAbsent(key, k -> new ArrayList<>()) for grouping
  • merge(key, 1, Integer::sum) for counting
  • entrySet() to loop over keys and values together

LinkedHashMap can even be a tiny LRU cache: turn on access order and override removeEldestEntry.

Diagram

HashMap

The default map: keys to values with O(1) average operations, no order, one null key allowed, not thread-safe. Learn the Java 8 methods: they replace most "check, then put" code. The "HashMap internals" stage explains exactly how it works.

Java
Map<String, Integer> seats = new HashMap<>();
seats.put("java", 30);
seats.getOrDefault("go", 0);                         // 0
seats.putIfAbsent("sql", 20);
seats.merge("java", -1, Integer::sum);               // 29: book one seat
seats.computeIfAbsent("docker", k -> loadSeats(k));  // load only if missing
for (Map.Entry<String, Integer> e : seats.entrySet()) {
    System.out.println(e.getKey() + " -> " + e.getValue());
}
HashMap lab

LinkedHashMap

A HashMap that remembers insertion order (or access order, for LRU caches). Use it when the order of keys matters, for example building JSON responses or showing "recently viewed" items. "HashMap vs LinkedHashMap" shows the LRU cache.

Java
Map<String, Object> json = new LinkedHashMap<>();
json.put("id", 101);
json.put("title", "Streams");
json.put("minutes", 12);
System.out.println(json);     // {id=101, title=Streams, minutes=12}   always in this order
LinkedHashMap lab

TreeMap

Keys kept sorted (natural order or a Comparator), stored in a red-black tree, so operations are O(log n). Its navigation methods make range questions easy: firstKey, lastKey, floorKey, ceilingEntry, headMap, tailMap and subMap. No null keys with natural ordering.

Java
TreeMap<Integer, String> grades = new TreeMap<>(Map.of(90, "A", 75, "B", 60, "C", 0, "F"));

System.out.println(grades.floorEntry(82).getValue());   // B   the highest threshold <= 82
System.out.println(grades.floorEntry(95).getValue());   // A
System.out.println(grades.headMap(75));                 // {0=F, 60=C}   keys below 75
System.out.println(grades.descendingMap());             // {90=A, 75=B, 60=C, 0=F}
TreeMap lab

Hashtable (legacy)

The Java 1.0 map: every method synchronized, no null keys or values, older Enumeration API. It's kept only for old code. Use HashMap in single-threaded code and ConcurrentHashMap when threads share the map; see "HashMap vs Hashtable".

ConcurrentHashMap lab

ConcurrentHashMap

The map to use when several threads read and write. Reads don't lock, writes lock only one bucket, and putIfAbsent, computeIfAbsent, compute and merge are atomic. No null keys or values. See "HashMap vs ConcurrentHashMap" for how it works.

Java
Map<String, Integer> activeUsers = new ConcurrentHashMap<>();
activeUsers.merge("/learn/streams", 1, Integer::sum);                      // safe from any thread
activeUsers.computeIfPresent("/learn/streams", (page, n) -> n > 1 ? n - 1 : null);   // null removes
ConcurrentHashMap lab

Special maps: EnumMap, WeakHashMap and IdentityHashMap

  • EnumMap: enum keys, backed by an array. The fastest map when keys are enum constants.
  • WeakHashMap: holds its keys weakly, so an entry disappears once nothing else references the key. Useful for caches attached to objects you don't own. (String literals and small Integers are never collected, so don't use them as keys.)
  • IdentityHashMap: compares keys with == instead of equals(). Used for graph algorithms and serialization frameworks that track object identity.

Example

Java
Map<String, Integer> wordCount = new HashMap<>();
for (String w : "to be or not to be".split(" ")) {
    wordCount.merge(w, 1, Integer::sum);             // {to=2, be=2, or=1, not=1}
}

Map<String, List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Pune", k -> new ArrayList<>()).add("Asha");

TreeMap<Integer, String> tiers = new TreeMap<>(Map.of(0, "Bronze", 1000, "Silver", 5000, "Gold"));
System.out.println(tiers.floorEntry(3200).getValue());   // Silver

class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;
    LruCache(int capacity) {
        super(16, 0.75f, true);                          // true = access order
        this.capacity = capacity;
    }
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

for (Map.Entry<String, Integer> e : wordCount.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

Common mistake

Using a mutable object as a key and changing it after putting it in. The entry becomes unreachable.

Under the hood

Looping over keySet() and calling get() does two lookups per entry; loop over entrySet() instead. HashMap allows one null key, while ConcurrentHashMap, Map.of and a naturally ordered TreeMap reject null keys. For a real cache with expiry and size limits, use Caffeine or Spring's cache support rather than a hand-made LRU.

Check yourself

Which method counts occurrences in one call?

How this connects

Part of Java 8 and collections, practically.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.