CKTIS / Java
Neighboring keys in NavigableMap
Find the closest stored key below or above a search key, with or without including a key that compares equal.
Version: Java SE 21
Syntax
K lowerKey(K key);
K floorKey(K key);
K ceilingKey(K key);
K higherKey(K key);Use NavigableMap.lowerKey/floorKey/ceilingKey/higherKey to find stored keys in a java.util.NavigableMap<K, V>. The search key q need not be in the map. lowerKey(q) picks the greatest key < q, floorKey(q) the greatest key <= q, ceilingKey(q) the smallest key >= q, and higherKey(q) the smallest key > q.
These relations follow the map’s ordering: either the keys’ natural order or the order defined by a Comparator. A key counts as equal for navigation when the comparison returns 0. In that case, floorKey and ceilingKey can return the stored key, whereas lowerKey and higherKey skip it.
The methods return only a key of type K, not a value or a key–value pair. If no key qualifies, including when the map is empty, the result is null. If the map allows a null key, that result can also mean the null key was found. To get both the key and its value or to distinguish those cases, use the corresponding lowerEntry, floorEntry, ceilingEntry, or higherEntry method: it returns a Map.Entry<K, V> for a match and null for no match.
A missing match is not an invalid argument: passing null can cause a NullPointerException if the map does not allow null keys. For example, in JDK 21, all four methods return null on an empty, naturally ordered TreeMap even when the search key is null, because there is no stored key to compare it with. A key that cannot be compared with keys in the map causes ClassCastException.
Examples
import java.util.NavigableMap;
import java.util.TreeMap;
public class NeighborKeys {
public static void main(String[] args) {
NavigableMap<Integer, String> map = new TreeMap<>();
map.put(10, "A");
map.put(50, "B");
map.put(90, "C");
printNeighbors(map, 75);
printNeighbors(map, 50);
System.out.println("lowerKey(10): " + map.lowerKey(10));
System.out.println("higherKey(90): " + map.higherKey(90));
}
private static void printNeighbors(NavigableMap<Integer, String> map, int key) {
System.out.println(key + ": " + map.lowerKey(key) + " / " + map.floorKey(key)
+ " / " + map.ceilingKey(key) + " / " + map.higherKey(key));
}
}Result
75: 50 / 50 / 90 / 90 50: 10 / 50 / 50 / 90 lowerKey(10): null higherKey(90): null
The results are printed in `lowerKey`, `floorKey`, `ceilingKey`, `higherKey` order. For `75`, they are `50 / 50 / 90 / 90`. For the stored key `50`, only the methods that include equality return `50`. There is no neighbor below `10` or above `90`, so the last two results are `null`.
Related lessons
- Java · Lesson 20 · Advanced · Version: 2