Sub topic 4
Navigating by key: first, last, floor and ceiling
This chapter assumes you know how maps and sets work, can read Big-O notation, and understand binary search. It also assumes you have met the ordered map interface, where keys are kept in a defined order.
Why navigation matters
A hash map answers one question: is this exact key present? An ordered map can also answer questions about neighbors. Which key comes just before 85? What is the smallest key at or above 42? These are navigation operations. They need the keys to be sorted, so a hash map cannot offer them efficiently.
The six core operations
Java's NavigableMap and NavigableSet interfaces name them most clearly. Other languages offer the same ideas under different names.
| Operation | Returns | Boundary |
|---|---|---|
| `firstKey()` | Smallest key | None |
| `lastKey()` | Largest key | None |
| `floorKey(k)` | Greatest key less than or equal to `k` | Inclusive |
| `ceilingKey(k)` | Smallest key greater than or equal to `k` | Inclusive |
| `lowerKey(k)` | Greatest key strictly less than `k` | Exclusive |
| `higherKey(k)` | Smallest key strictly greater than `k` | Exclusive |
Floor and lower look downward. Ceiling and higher look upward. The pairs differ only in whether an exact match counts.
When the query is 80 itself, floor and ceiling both return 80. Lower returns 70 and higher returns 90.
Worked example: a grade table
A table of thresholds is a common use. The key is the lowest score for a grade, and floorEntry finds the grade for any score.
import java.util.TreeMap;
public class GradeLookup {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
int score = 85;
System.out.println(grades.floorEntry(score).getValue()); // B
System.out.println(grades.ceilingKey(score)); // 90
System.out.println(grades.firstKey()); // 60
System.out.println(grades.lastKey()); // 90
}
}The score 85 is not a key. floorEntry finds 80, the greatest key not above 85, and returns its value B. No loop over thresholds is needed.
Handling missing results
If no key satisfies the condition, these methods return null. For example, floorEntry(50) returns null here because nothing is at or below 50. Calling .getValue() on that result throws a NullPointerException. The firstKey() and lastKey() methods behave differently: on an empty map they throw NoSuchElementException. Check for these cases before you dereference the result.
import java.util.Map;
import java.util.TreeMap;
public class SafeFloor {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(60, "D");
grades.put(70, "C");
Map.Entry<Integer, String> entry = grades.floorEntry(50);
String grade = (entry == null) ? "F" : entry.getValue();
System.out.println(grade); // F
}
}Cost
In a balanced search tree, each navigation call walks one root-to-leaf path, so it costs O(log n). firstKey() and lastKey() follow the leftmost or rightmost path, which is also O(log n) in a plain tree. Some implementations cache the ends. In a sorted array, you find the position with binary search in O(log n), and the first and last keys are O(1).
Exercise
A TreeSet contains 10, 20, 30 and 40. What do floor(25), ceiling(25), lower(30) and higher(30) return?
Show answer
floor(25) returns 20, the greatest element at or below 25. ceiling(25) returns 30, the smallest element at or above 25. lower(30) returns 20 because an exact match does not count. higher(30) returns 40 for the same reason.
Exercise
Why does grades.floorEntry(50).getValue() fail on the grade table, and how do you fix it?
Show answer
No key is at or below 50, so floorEntry returns null and calling getValue on null throws a NullPointerException. Store the result in a variable, check it for null, and use a default such as "F" when it is null.