TreeMap: Sorted Key-Value Pairs
Use TreeMap to maintain sorted order and navigate with firstKey, lastKey, floorKey, and ceilingKey.
What is TreeMap?
TreeMap is a sorted map implementation backed by a Red-Black tree. Keys are maintained in ascending natural order (or custom comparator order). All basic operations are O(log n).
import java.util.TreeMap;
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Charlie", 85);
scores.put("Alice", 92);
scores.put("Bob", 78);
// Iteration is in key order: Alice, Bob, Charlie
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}firstKey, lastKey, floorKey, ceilingKey
TreeMap's NavigableMap interface exposes navigation methods for finding keys relative to a given value:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "ten"); map.put(20, "twenty"); map.put(30, "thirty"); map.put(40, "forty");
System.out.println(map.firstKey()); // 10
System.out.println(map.lastKey()); // 40
System.out.println(map.floorKey(25)); // 20 (largest key ≤ 25)
System.out.println(map.ceilingKey(25)); // 30 (smallest key ≥ 25)
System.out.println(map.lowerKey(20)); // 10 (strictly less)
System.out.println(map.higherKey(20)); // 30 (strictly greater)All lessons in this course
- TreeMap: Sorted Key-Value Pairs
- Submaps and Range Views
- TreeSet and NavigableSet
- Custom Ordering in Tree Collections