Video in progress
How have you used TreeMap methods like floorKey, ceilingEntry and subMap on a real problem?
TreeMap is a NavigableMap, and it gives you "nearest smaller/larger key" and range queries in O(log n). It is very handy, for example, for finding a fee tier by amount or for pulling the entries in a time window.
📖 Answer
The classic example is a tiered tariff. Finding which tier an amount falls into without an if-else chain:
NavigableMap<Long, Integer> feePercent = new TreeMap<>(Map.of(
0L, 3,
1_000_000L, 2,
10_000_000L, 1
));
int fee = feePercent.floorEntry(2_500_000L).getValue(); // 2
floorEntry(x) returns the greatest key that is less than or equal to x. Similar ones: ceilingKey (≥), lowerKey (<), higherKey (>).
A time window:
NavigableMap<Instant, Event> events = new TreeMap<>();
SortedMap<Instant, Event> lastHour =
events.subMap(now.minus(1, ChronoUnit.HOURS), now); // [from, to)
subMap, headMap and tailMap return views, not copies, so changes in the original map show up in them too.
Other useful ones: firstEntry(), pollFirstEntry() (takes and removes), descendingMap(). If no key is found, these methods return null, so watch out for an NPE, as with floorEntry(-5) in the example above.
Sign up to mark studied questions and save your progress.