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
(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.HashMap (Java 1.4) is aLinkedHashMap 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 aHashMap .HashMap (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.TreeMap
| Property | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Iteration order | Unspecified | Insertion or access | Sorted by key |
getput | O(1) | O(1) | O(log n) |
| Null keys | One allowed | One allowed | Not with natural order |
| Key requirement | equalshashCode | equalshashCode | Comparable |
| Entry object (compressed references) | About 32 bytes | About 40 bytes | About 40 bytes |
SequencedMap | No | Yes | Yes (also NavigableMap |
| Best for | Lookups | Predictable order, caches | Sorted output, ranges |
The entry sizes follow from the fields each entry object holds: a LinkedHashMapHashMapTreeMap
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.
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:
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
printedHashMap first, an order that comes from the hash codes.mumbai - The
kept insertion order:LinkedHashMap ,zurich ,athens ,mumbai .berlin - The
sorted the keys alphabetically.TreeMap - The comparator
sorted longest names first, with alphabetical order breaking ties, so the addedcomparing(String::length).reversed().thenComparing(naturalOrder()) came last. A comparator without the tie-breaker would treatrome andathens , both six letters, as the same key.berlin
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.
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:
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:
stayed first. Removing and re-adding moves it to the end.a - Java 21 added
andputFirst toputLast , which insert or move a key to one end.LinkedHashMap - In access order, both
andget count as access and move the key to the end, leavinggetOrDefault , the least recently used, at the front.z - A
uses its comparator, notTreeMap , to decide whether keys are the same. Withequals ,CASE_INSENSITIVE_ORDER replaced the value ofAPPLE , and the first spelling stayed as the key.Apple - A
with natural order rejects aTreeMap key, because it cannot compare it.null andHashMap accept one.LinkedHashMap
Sequenced methods (Java 21)
Java 21 (JEP 431) made LinkedHashMapTreeMapSequencedMap
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:
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}
andfirstEntry() read the ends of alastEntry() without iterating; before Java 21 this needed an iterator or a loop to the end.LinkedHashMap returns a view in reverse order, without copying.reversed() removes and returns the first entry, here the gold ranking from apollFirstEntry() .TreeMap
An LRU cache in a few lines
An access-ordered LinkedHashMapremoveEldestEntry
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:
full: [a, b, c]
after get(a): [b, c, a]
after put(d): [c, a, d]
b still cached? false
- Reading
moved it to the most-recent end, so whena arrived,d was the eldest entry and was evicted.b is called after every insertion; returningremoveEldestEntry removes the first entry in the linked order.true- The class is not thread-safe. Wrap it with
, or use a caching library such as Caffeine for concurrent caches with expiry.Collections.synchronizedMap
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.
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):
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
took anything from a little less time than theLinkedHashMap 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. ItsHashMap was no slower than theget one in any run. Keeping insertion order costs memory and insertion time, not lookup time.HashMap was several times slower forTreeMap and often more than ten times slower forput : each operation walks about 19 levels of the tree and compares keys at every step.get- Iteration was fast for all three.
iterates its linked list rather than the bucket array, which also makes its iteration time independent of the table capacity.LinkedHashMap
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
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);
}
}
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
came out astoMap in a[plum, apple, kiwi, pear, Fig, Banana] . The four-argumentHashMap withtoMap kept the sorted order, with the capitalised words first because uppercase letters sort before lowercase.LinkedHashMap::new - Copying the
into aHashMap kept the hash order it was given, because that was the order in which the entries arrived. To sort, copy into aLinkedHashMap .TreeMap - The copy made from a variable of type
kept the case-insensitive comparator, while the copy of the same object through aTreeMap variable lost it and sortedMap andBanana first. Java picks the constructor from the variable's declared type:Fig keeps the ordering, andTreeMap(SortedMap) is documented to use natural ordering.TreeMap(Map) - A
in reverse order equalled theTreeMap , although theirLinkedHashMap output differed.toString compares only the mappings, so a test that checks order must compare key lists, for exampleMap.equals .new ArrayList<>(map.keySet()) - No map keeps entries sorted by value. Streaming the entries, sorting with
and collecting into acomparingByValue().thenComparing(comparingByKey()) gave a snapshot ordered by word length, with ties in key order. The snapshot does not re-sort when values change later.LinkedHashMap
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.
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()
heap retained per entry, 1,000,000 entries (smallest of 3 measurements):
HashMap 41.5 bytes
LinkedHashMap 49.5 bytes
TreeMap 40.0 bytes
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.TreeMap 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.HashMap needed about 49 to 50 bytes, the same array share plus a 40-byte entry with itsLinkedHashMap andbefore links. Keeping insertion order costs about a fifth more memory than aafter .HashMap
Boxed keys and values usually cost more than the map itself: each Integer
Which map to use
| You need | Use |
|---|---|
| Fast lookups, order does not matter | HashMap |
| Iteration in insertion order | LinkedHashMap |
| Least recently used first, eviction | LinkedHashMapremoveEldestEntry |
| Sorted keys or custom key order | TreeMap |
| Nearest key, ranges, first and last by key | TreeMap |
| Ends and reversed view, insertion order | LinkedHashMap |
| Sorted and concurrent | ConcurrentSkipListMap |
| Enum keys | EnumMap |
How the hash table underneath HashMapLinkedHashMap