CKTIS / Java
NavigableMap — neighboring keys and range views
NavigableMap extends SortedMap with neighboring-key lookups and range views whose boundary inclusion can be controlled.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
NavigableMap<K, V> map;
K lowerKey(K key);
K floorKey(K key);
K ceilingKey(K key);
K higherKey(K key);
NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive);
NavigableMap<K, V> headMap(K toKey, boolean inclusive);
NavigableMap<K, V> tailMap(K fromKey, boolean inclusive);NavigableMap<K, V> extends SortedMap<K, V>. One implementation is TreeMap. Comparisons follow natural key ordering or a Comparator, not insertion order.
For an argument key, lowerKey returns the greatest key < key, floorKey the greatest <= key, ceilingKey the least >= key, and higherKey the least > key. No match means null; avoid automatically unboxing that result to a primitive.
subMap(fromKey, fromInclusive, toKey, toInclusive) selects a range between boundaries; headMap(toKey, inclusive) selects keys below an upper boundary; tailMap(fromKey, inclusive) selects keys above a lower boundary. A true flag includes that boundary. Overloads without flags mean [fromKey, toKey), an excluded upper boundary, and an included lower boundary, respectively; they declare a SortedMap result rather than NavigableMap.
These are backed views, not copies: supported changes are visible in both directions. Inserting an out-of-range key throws IllegalArgumentException; fromKey greater than toKey is also invalid.
Reference identifiers covered by this entry: NavigableMap.lowerKey, NavigableMap.floorKey, NavigableMap.ceilingKey, NavigableMap.higherKey, NavigableMap.subMap, NavigableMap.headMap, NavigableMap.tailMap.
Examples
import java.util.NavigableMap;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
NavigableMap<Integer, String> map = new TreeMap<>();
map.put(10, "A");
map.put(20, "B");
map.put(30, "C");
System.out.println(map.lowerKey(20));
System.out.println(map.floorKey(20));
System.out.println(map.ceilingKey(20));
System.out.println(map.higherKey(20));
System.out.println(map.lowerKey(10));
NavigableMap<Integer, String> range = map.subMap(10, true, 30, false);
System.out.println(range);
System.out.println(map.headMap(20, true));
System.out.println(map.tailMap(20, false));
range.put(20, "updated");
System.out.println(map.get(20));
}
}Result
10
20
20
30
null
{10=A, 20=B}
{10=A, 20=B}
{30=C}
updatedThe displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.