Java 20: TreeMap & Sorted Collections
easy⏱ 5 mincoursejava
TreeMap properties
Natural ordering by key (or a provided Comparator). All ops O(log n). firstKey(), lastKey(), ceilingKey(k), floorKey(k), higherKey(k), lowerKey(k) — unique powers of the tree. Iteration is in sorted order, at the cost of ~2x overhead per put/get vs HashMap.
NavigableMap / NavigableSet
Both TreeMap and TreeSet implement NavigableMap/NavigableSet — giving you subMap(from, to) views that are live (modifications propagate). Great for range queries, time-series bucketing, leaderboard top-N.
TreeMap<LocalDate, Event> events = ...;
SortedMap<LocalDate, Event> today =
events.subMap(LocalDate.now(), LocalDate.now().plusDays(1));
Build a range-query map
Implement a SortedBag<V> over numeric keys using a sorted array. Methods: put(k, v), get(k), rangeClosed(lo, hi): V[]. Use binary search to locate the range boundaries. Insert 100 entries and query a 10-key window — should be O(log n + 10).
LinkedHashMap preserves insertion order
Between HashMap (unordered, fastest) and TreeMap (sorted, slowest) sits LinkedHashMap: O(1) ops plus insertion-order iteration. It also supports access-order mode for building LRU caches (removeEldestEntry hook).
Quiz: When TreeMap beats HashMap
When should you reach for TreeMap? When you need range queries, ordered iteration, or nearest-key lookup. For pure key-value storage with no ordering needs, HashMap is faster.