HashMap vs TreeMap vs LinkedHashMap (and ConcurrentHashMap)
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)"HashMap, LinkedHashMap or TreeMap?" tests whether you choose a map from the requirement: order, speed and nulls. Interviewers then ask for an LRU cache, a nearest-key lookup or a thread-safe counter to see if you can apply the choice.
Ordering, complexity and null rules side by side
A TreeMap is a Map that keeps its keys sorted, by their natural order or by a Comparator. It is a red-black tree, so get and put take O(log n) time.
Interviewers usually ask for this comparison as a table. The program prints the same marks in three maps, so you can see the three orders.
Example 1 · Same marks, three different orders
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.TreeMap;
public class MapOrderDemo { public static void main(String[] args) { String[] subjects = {"Physics", "Maths", "Chemistry", "English"}; int[] marks = {78, 92, 65, 81};
Map<String, Integer> hash = new HashMap<>(); Map<String, Integer> linked = new LinkedHashMap<>(); Map<String, Integer> tree = new TreeMap<>(); for (int i = 0; i < subjects.length; i++) { hash.put(subjects[i], marks[i]); linked.put(subjects[i], marks[i]); tree.put(subjects[i], marks[i]); } System.out.println("HashMap " + hash); System.out.println("LinkedHashMap " + linked); System.out.println("TreeMap " + tree);
try { tree.put(null, 0); } catch (NullPointerException e) { System.out.println("TreeMap null key: NullPointerException"); } }}HashMap {Maths=92, English=81, Chemistry=65, Physics=78}
LinkedHashMap {Physics=78, Maths=92, Chemistry=65, English=81}
TreeMap {Chemistry=65, English=81, Maths=92, Physics=78}
TreeMap null key: NullPointerExceptionWhat this code does
- LinkedHashMap repeats the insertion order and TreeMap sorts the keys alphabetically. HashMap's order comes from the hash codes, so treat it as random.
- TreeMap must compare every key, and comparing
nullthrows aNullPointerException.
Say it row by row:
HashMap: no guaranteed order. O(1) average get and put. One null key, null values allowed.LinkedHashMap: insertion order (or access order, if asked). O(1) average. Same null rules as HashMap.TreeMap: keys sorted by natural order or aComparator. O(log n), as it is a red-black tree. No null key with natural order; null values allowed.ConcurrentHashMap: no order, O(1) average, thread-safe. No null keys or values.Hashtableis its old, slower ancestor with the same null rule.
LinkedHashMap access order and an LRU cache
An LRU cache (least recently used) keeps a fixed number of items and removes the one that was not used for the longest time when a new item arrives.
An LRU cache keeps recent items and drops the one unused for the longest time. The program builds one by overriding removeEldestEntry in a LinkedHashMap with access order.
Example 2 · An LRU cache of recently opened courses
import java.util.LinkedHashMap;import java.util.Map;
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; }}
public class LruCacheDemo { public static void main(String[] args) { LruCache<String, String> recent = new LruCache<>(3); recent.put("Java", "lesson 12"); recent.put("SQL", "lesson 4"); recent.put("DSA", "lesson 30"); System.out.println("Start: " + recent.keySet());
recent.get("Java"); System.out.println("After get: " + recent.keySet());
recent.put("Git", "lesson 2"); System.out.println("After put Git: " + recent.keySet()); System.out.println("SQL still cached? " + recent.containsKey("SQL")); }}Start: [Java, SQL, DSA] After get: [SQL, DSA, Java] After put Git: [DSA, Java, Git] SQL still cached? false
What this code does
- The
trueargument switches on access order, soget("Java")moves Java to the end, the most recently used spot. - Adding Git makes the size 4, so
removeEldestEntryreturnstrueand the front entry, SQL, is removed. That is the whole LRU cache.
A LinkedHashMap is a HashMap plus a doubly linked list through its entries. By default the list follows insertion order. With the constructor new LinkedHashMap<>(16, 0.75f, true), it follows access order: every get or put moves that key to the end.
With access order, the least recently used item is always at the front. Override removeEldestEntry to return true when the size passes the limit, and LinkedHashMap removes the front entry after each put. Revise: LRU cache with LinkedHashMap (opens in a new tab).
Find the bug
Find the LRU cache bug
Each snippet should behave like an LRU cache. Tap the wrong line, then check the fix.
Reading a key must make it "recently used".
Round 1 of 3TreeMap navigation: floorKey, ceilingKey, headMap
floorKey(k) returns the largest key less than or equal to k, and ceilingKey(k) the smallest key greater than or equal to k. Both return null when there is no such key.
A TreeMap answers "nearest key" questions fast. The program finds the grade for a mark with floorKey, then slices the slabs with headMap and tailMap.
Example 3 · Grade slabs with floorKey, ceilingKey and headMap
import java.util.TreeMap;
public class GradeSlabDemo { public static void main(String[] args) { TreeMap<Integer, String> grades = new TreeMap<>(); grades.put(0, "F"); grades.put(40, "D"); grades.put(50, "C"); grades.put(60, "B"); grades.put(75, "A"); grades.put(90, "O");
for (int marks : new int[] {38, 50, 74, 95}) { System.out.println(marks + " -> " + grades.get(grades.floorKey(marks))); } System.out.println("Next slab above 74 starts at " + grades.ceilingKey(74)); System.out.println("Slabs below 60: " + grades.headMap(60)); System.out.println("Slabs from 75: " + grades.tailMap(75)); System.out.println("Lowest " + grades.firstKey() + ", highest " + grades.lastKey()); }}38 -> F
50 -> C
74 -> B
95 -> O
Next slab above 74 starts at 75
Slabs below 60: {0=F, 40=D, 50=C}
Slabs from 75: {75=A, 90=O}
Lowest 0, highest 90What this code does
floorKey(74)is 60, the largest slab start not above 74, so 74 marks get a B. Each lookup is O(log n).headMap(60)leaves 60 out, whiletailMap(75)includes 75. Both are live views of the same tree.
headMap(k) is a view of all keys below k (k excluded), and tailMap(k) of all keys from k upwards (k included). firstKey() and lastKey() give the ends. Grade slabs, fare slabs and "next free slot" problems are a natural fit.
Predict the output
Predict the TreeMap answer
The map t has the keys 10, 20, 30 and 40. Pick the result.
Round 1 of 3
What does t.higherKey(30) return?
HashMap vs Hashtable vs ConcurrentHashMap in one minute
A ConcurrentHashMap is a thread-safe Map. Reads mostly take no lock and a write locks only one bucket, so many threads can work at once. It allows no null keys and no null values.
Four threads update one map at the same time. The program counts votes with ConcurrentHashMap.merge and shows its null rules.
Example 4 · Four threads counting votes safely
import java.util.Hashtable;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentVotesDemo { public static void main(String[] args) throws InterruptedException { Map<String, Integer> votes = new ConcurrentHashMap<>(); Runnable booth = () -> { for (int i = 0; i < 10_000; i++) { votes.merge("Candidate A", 1, Integer::sum); } };
Thread[] booths = new Thread[4]; for (int i = 0; i < booths.length; i++) { booths[i] = new Thread(booth); booths[i].start(); } for (Thread t : booths) { t.join(); } System.out.println("Votes counted: " + votes.get("Candidate A"));
try { votes.put("NOTA", null); } catch (NullPointerException e) { System.out.println("ConcurrentHashMap null value: NullPointerException"); } Map<String, Integer> legacy = new Hashtable<>(); try { legacy.put(null, 1); } catch (NullPointerException e) { System.out.println("Hashtable null key: NullPointerException"); } }}Votes counted: 40000 ConcurrentHashMap null value: NullPointerException Hashtable null key: NullPointerException
What this code does
mergeis atomic in ConcurrentHashMap, so all 40,000 increments survive. With a plain HashMap the count would often come out lower.joinwaits for every thread, so the total is printed only after all booths finish. Both thread-safe maps rejectnull.
Hashtable is a legacy class (Java 1.0) whose every method is synchronized, so one lock blocks the whole table. The atomic methods of ConcurrentHashMap such as merge and computeIfAbsent make check-then-update safe.
Plain HashMap is not thread-safe: two threads writing at once can lose updates. Collections.synchronizedMap(map) adds one lock around a HashMap, which is safe but slow under load.
ConcurrentModificationException; they may or may not show changes made during the loop.Choosing the right map
Start from the requirement, not the class name. These four questions cover almost every interview scenario.
- Only fast lookups, order does not matter →
HashMap. - Keep the order items were added, or build an LRU cache →
LinkedHashMap. - Need sorted keys, ranges, or the nearest key (floor or ceiling) →
TreeMap. - Several threads update the map →
ConcurrentHashMap(neverHashtablein new code).
Next step
Check your understanding
12 quick questions