← The curriculum
§ 6.05 · Data Structures in Java

TreeMap, TreeSet, and ordered structures

Red-black trees under the hood. O(log n) sorted access, range queries, and floor/ceiling lookups.

Intermediate · 26 minute read
Try it yourself
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 6.05.01

Ordered, not just sorted

TreeMap keeps its entries in key order at all times. Iterating a TreeMap gives you a sorted sequence; firstKey, lastKey, ceilingKey, and floorKey all run in O(log n). Compare that with HashMap, where iteration order is unspecified.

§ 6.05.02

Red-black trees

The internal structure is a red-black tree — a self-balancing binary search tree where every path from root to leaf differs in length by at most a factor of two. That guarantee keeps get, put, and remove all at O(log n) regardless of insertion order.

§ 6.05.03

Range views

headMap(k), tailMap(k), and subMap(lo, hi) return live views over a slice of the map. Modifying the view modifies the source and vice versa. These are ideal for pulling out ranges — say, all events between two timestamps — without copying.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 6.05.04

Custom ordering

Pass a Comparator to the constructor to override natural ordering: new TreeMap<>(Comparator.reverseOrder()). For custom types, either implement Comparable for a natural order or pass a Comparator — pick one and stick to it, since mixing them is a common bug source.

§ 6.05.05

TreeSet — sorted uniqueness

TreeSet is the set flavor of the same structure. It gives you sorted iteration, first, last, ceiling, floor, headSet, tailSet, and O(log n) membership. Use it when you need both dedupe and order.

§ 6.05.06

When to use it

Reach for TreeMap/TreeSet when you need sorted iteration, range queries, or nearest-neighbor lookups (floor/ceiling). Stick with HashMap/HashSet when order doesn't matter — hashing is faster and more memory-efficient.