TreeMap
TreeMap is a map whose keys stay sorted. It is a red-black tree. get, put, and remove are O(log n). It implements NavigableMap for range queries.
Detailed Explanation
When you need the next key above x, or every entry between two dates, a hash table cannot help without scanning everything. A TreeMap keeps keys in a balanced binary search tree. In-order traversal is sorted order. firstKey, lastKey, ceilingKey, floorKey, subMap, headMap, and tailMap are O(log n) plus the size of the result.
Ordering comes from Comparable on the keys, or from a Comparator you pass to the constructor. The comparator must be consistent with equals if you want the Map contract to hold: two keys that compare as 0 are the same key to the tree, even if equals is false. Mixing that up drops entries you thought were distinct.
null keys are forbidden when you use natural order, because compareTo cannot run on null. A comparator that treats null as smallest can allow one null key. Values may be null. The map is not thread-safe.
You reach for TreeMap when the sort is the feature: a leaderboard, a time index, a range of prices. You keep HashMap when you only look up by exact key. You use ConcurrentSkipListMap when threads share a sorted map. You use LinkedHashMap when you want insertion order, not key order.
The cost of O(log n) is visible on large maps and hot paths; a hash map is faster for raw get/put. The cost of a bad comparator is a tree that violates transitivity and can misbehave indefinitely. Do not change a key's comparison fields after insert. Do not use TreeMap as a default map "to be safe"; you pay for order you may not use.
subMap views are backed by the same tree. Changing the view changes the map. Endpoints are inclusive or exclusive depending on the overload; the low, high two-argument subMap is inclusive-exclusive. Read the method you called.
Code Examples
import java.util.TreeMap;
public class Scores {
public static void main(String[] args) {
TreeMap<Integer, String> ranks = new TreeMap<>();
ranks.put(10, "bo");
ranks.put(3, "ana");
ranks.put(7, "cy");
System.out.println(ranks.keySet()); // prints: [3, 7, 10]
System.out.println(ranks.ceilingKey(6)); // prints: 7
System.out.println(ranks.headMap(7)); // prints: {3=ana}
}
}import java.util.Comparator;
import java.util.TreeMap;
public class ByLength {
public static void main(String[] args) {
TreeMap<String, Integer> words = new TreeMap<>(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
words.put("aa", 1);
words.put("b", 2);
words.put("ccc", 3);
System.out.println(words.keySet()); // prints: [b, aa, ccc]
}
}Common Gotchas
Keys must be comparable, or you must pass a comparator
putting a plain object throws `ClassCastException`.
A comparator that disagrees with `equals` breaks the `Map` contract
keys that compare 0 overwrite each other.
`subMap` is a view
`clear()` on the view deletes those keys from the original map.
`TreeMap` is not thread-safe
use `ConcurrentSkipListMap` for concurrent sorted keys.