NavigableMap and NavigableSet
A sorted map or set can answer questions a hash map cannot: what is the nearest key below or above a value, which keys fall in a range, what comes first or last. NavigableMap and NavigableSet, implemented by TreeMap and TreeSet, provide those operations. This page explains how they work, runs each kind of query, uses range views, and measures what sorting costs.
Contents
What navigation adds to a sorted collection Nearest matches: floor, ceiling, lower and higher Bands and thresholds with floorEntry Range views Sets with a comparator, and what sorting costs Traps: comparators, snapshots, nulls and changing keys Java 21 sequenced views and concurrent navigation When to use navigation
What navigation adds to a sorted collection
TreeMapTreeSetNavigableMapNavigableSet
The navigation methods return nullfirstlastNoSuchElementException
| Method | Returns | Best for |
|---|---|---|
floor(x)floorKeyfloorEntry | Largest key ≤ x | Bands, versions in effect at a time |
ceiling(x)ceilingKeyceilingEntry | Smallest key ≥ x | Next available slot |
lower(x)higher(x) | Strictly below or above x | Previous and next neighbours |
first()last()pollFirst()pollLast() | The ends; poll also removes | Smallest or largest; simple queues |
subSetheadSettailSetsubMapheadMaptailMap | A range view | Time windows, alphabetical ranges |
descendingSet()descendingMap() | A reverse-order view | Newest first, highest first |
ConcurrentSkipListMapConcurrentSkipListSet
Nearest matches: floor, ceiling, lower and higher
A set of appointment start times in minutes, with gaps between them, shows each nearest-match query and what happens when there is no answer.
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;
public class NearestMatch {
static void show(String call, Integer result, String meaning) {
System.out.printf("%-12s = %-4s (%s)%n", call, result, meaning);
}
public static void main(String[] args) {
// Available appointment times, in minutes after 9:00
NavigableSet<Integer> slots = new TreeSet<>(List.of(0, 30, 90, 120, 240));
int wanted = 100;
show("floor(100)", slots.floor(wanted), "largest <= 100");
show("ceiling(100)", slots.ceiling(wanted), "smallest >= 100");
show("lower(90)", slots.lower(90), "largest < 90");
show("higher(90)", slots.higher(90), "smallest > 90");
show("ceiling(300)", slots.ceiling(300), "nothing that late");
System.out.println("first = " + slots.first() + ", last = " + slots.last());
System.out.println("descending: " + slots.descendingSet());
// pollFirst removes and returns the smallest: book the earliest slot
System.out.println("booked " + slots.pollFirst() + ", left " + slots);
}
}
Output:
floor(100) = 90 (largest <= 100)
ceiling(100) = 120 (smallest >= 100)
lower(90) = 30 (largest < 90)
higher(90) = 120 (smallest > 90)
ceiling(300) = null (nothing that late)
first = 0, last = 240
descending: [240, 120, 90, 30, 0]
booked 0, left [30, 90, 120, 240]
found 90, the latest slot at or before 100, andfloor(100) found 120, the earliest at or after it.ceiling(100) andlower exclude the value itself:higher is 30 even though 90 is in the set.lower(90) returnedceiling(300) , so check results before unboxing them into annull .int reverses the order, anddescendingSet() removed and returned the earliest slot, booking it.pollFirst()
Bands and thresholds with floorEntry
Shipping prices by order value are a classic band lookup: each key is the lower bound of a band, and the right band for any amount is the entry at or below it. The amounts tested include values exactly on and between the bounds.
import java.util.NavigableMap;
import java.util.TreeMap;
public class PriceBands {
// Lower bound of each band -> shipping cost. floorEntry finds the band for any amount.
static final NavigableMap<Double, String> SHIPPING = new TreeMap<>();
static {
SHIPPING.put(0.0, "7.99");
SHIPPING.put(25.0, "4.99");
SHIPPING.put(50.0, "2.99");
SHIPPING.put(100.0, "free");
}
public static void main(String[] args) {
for (double total : new double[] {9.50, 25.00, 49.99, 75.00, 250.00}) {
String cost = SHIPPING.floorEntry(total).getValue();
System.out.printf("order %7.2f -> shipping %s%n", total, cost);
}
}
}
Output:
order 9.50 -> shipping 7.99
order 25.00 -> shipping 4.99
order 49.99 -> shipping 4.99
order 75.00 -> shipping 2.99
order 250.00 -> shipping free
returned the band whose lower bound is at or below the amount, so 25.00 and 49.99 both fell into the 25 band, and 250.00 into the free-shipping band.floorEntry(amount)- The same pattern fits tax brackets, grading scales, discount tiers and "which configuration version was active at time t". A chain of
statements does the same work but is harder to change.if - Include a band starting at the smallest possible value, here 0, so that
never returnsfloorEntry .null
Range views
Daily sales keyed by day of the month are queried by ranges. The program also writes through a view and tries to write outside it.
import java.util.NavigableMap;
import java.util.TreeMap;
public class RangeViews {
public static void main(String[] args) {
// Sales per day of the month
NavigableMap<Integer, Integer> sales = new TreeMap<>();
sales.put(1, 120);
sales.put(3, 80);
sales.put(7, 200);
sales.put(10, 50);
sales.put(14, 170);
sales.put(21, 90);
System.out.println("days 3..10 (inclusive): " + sales.subMap(3, true, 10, true));
System.out.println("before day 7: " + sales.headMap(7));
System.out.println("day 14 onwards: " + sales.tailMap(14, true));
// Views are live: writing through them changes the original
NavigableMap<Integer, Integer> firstWeek = sales.headMap(7, true);
firstWeek.put(5, 60);
System.out.println("original after put(5): " + sales);
try {
firstWeek.put(20, 1);
} catch (IllegalArgumentException e) {
System.out.println("put(20) into days 1..7: IllegalArgumentException");
}
int firstWeekTotal = firstWeek.values().stream().mapToInt(Integer::intValue).sum();
System.out.println("first-week total: " + firstWeekTotal);
System.out.println("entry at or before 12: " + sales.floorEntry(12));
System.out.println("descending keys: " + sales.descendingKeySet());
}
}
Output:
days 3..10 (inclusive): {3=80, 7=200, 10=50}
before day 7: {1=120, 3=80}
day 14 onwards: {14=170, 21=90}
original after put(5): {1=120, 3=80, 5=60, 7=200, 10=50, 14=170, 21=90}
put(20) into days 1..7: IllegalArgumentException
first-week total: 460
entry at or before 12: 10=50
descending keys: [21, 14, 10, 7, 5, 3, 1]
includes both ends. The two-argument forms follow the half-open convention:subMap(3, true, 10, true) excludes 7 andheadMap(7) includes 14.tailMap(14)- A view is live: putting day 5 through the first-week view added it to the original map.
- Putting a key outside the view's range, day 20 into days 1 to 7, threw
.IllegalArgumentException - Summing a view's values gives a range total without copying, here 460 for the first week.
found day 10, andfloorEntry(12) lists the days newest first.descendingKeySet()
Sets with a comparator, and what sorting costs
A TreeSetTreeMapHashMap
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
public class SetViewsAndCost {
public static void main(String[] args) {
NavigableSet<String> words = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
words.addAll(java.util.List.of("pear", "Apple", "fig", "Kiwi", "banana", "cherry"));
System.out.println("case-insensitive set: " + words);
System.out.println("subSet(b, c) [b, c): " + words.subSet("b", "c"));
System.out.println("subSet(b, true, cherry, true): "
+ words.subSet("b", true, "cherry", true));
System.out.println("tailSet(k): " + words.tailSet("k"));
NavigableSet<String> desc = words.descendingSet();
System.out.println("descendingSet view: " + desc + ", first " + desc.first());
System.out.println("pollFirst: " + words.pollFirst() + ", pollLast: " + words.pollLast()
+ ", left " + words);
// Cost: a TreeMap lookup is O(log n), a HashMap lookup O(1)
int n = 1000000;
Map<Integer, Integer> hash = new HashMap<>();
TreeMap<Integer, Integer> tree = new TreeMap<>();
for (int i = 0; i < n; i++) {
hash.put(i * 2, i);
tree.put(i * 2, i);
}
int[] probes = new Random(8).ints(1000000, 0, 2 * n).toArray();
System.out.printf("1,000,000 lookups in maps of %,d keys:%n", n);
System.out.printf(" HashMap.get %6.1f ms%n", best(() -> {
long s = 0;
for (int p : probes) {
Integer v = hash.get(p);
s += v == null ? 0 : v;
}
return s;
}));
System.out.printf(" TreeMap.get %6.1f ms%n", best(() -> {
long s = 0;
for (int p : probes) {
Integer v = tree.get(p);
s += v == null ? 0 : v;
}
return s;
}));
System.out.printf(" TreeMap.floorKey %6.1f ms (no HashMap equivalent)%n", best(() -> {
long s = 0;
for (int p : probes) {
Integer k = tree.floorKey(p);
s += k == null ? 0 : k;
}
return s;
}));
}
interface Work {
long run();
}
// Best of 3 runs, in milliseconds
static double best(Work w) {
long best = Long.MAX_VALUE;
for (int r = 0; r < 3; r++) {
long t0 = System.nanoTime();
if (w.run() < 0) {
throw new AssertionError();
}
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1e6;
}
}
Output (timings are rough; 2-CPU Linux machine, JDK 21):
case-insensitive set: [Apple, banana, cherry, fig, Kiwi, pear]
subSet(b, c) [b, c): [banana]
subSet(b, true, cherry, true): [banana, cherry]
tailSet(k): [Kiwi, pear]
descendingSet view: [pear, Kiwi, fig, cherry, banana, Apple], first pear
pollFirst: Apple, pollLast: pear, left [banana, cherry, fig, Kiwi]
1,000,000 lookups in maps of 1,000,000 keys:
HashMap.get 35.5 ms
TreeMap.get 805.4 ms
TreeMap.floorKey 841.5 ms (no HashMap equivalent)
- With
,CASE_INSENSITIVE_ORDER andApple sort among the lowercase words.Kiwi includessubSet("b", "c") and excludesb , so it holds onlyc ; the four-argument version can include both ends.banana is a reverse view of the same set, anddescendingSet() andpollFirst removed the two ends.pollLast- A
took from several to more than twenty times as long asTreeMap.get across runs: each lookup follows about 20 tree links through scattered memory instead of one hash bucket.HashMap.get costs the same asfloorKey , and aget cannot answer it at all without scanning every key. Use a tree when you need order or nearest-key queries, and a hash map when you only need exact lookups.HashMap
Traps: comparators, snapshots, nulls and changing keys
A tree map or set finds elements only by comparing them, never by calling equalshashCode
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class NavigationTraps {
public static void main(String[] args) {
// 1. A comparator that disagrees with equals silently merges elements
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
names.addAll(List.of("Apple", "apple", "APPLE", "Banana"));
System.out.println("case-insensitive TreeSet: " + names + ", size " + names.size());
Set<String> hash = new HashSet<>(List.of("Apple", "Banana"));
Set<String> lower = new HashSet<>(List.of("apple", "banana"));
Set<String> tree = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
tree.addAll(lower);
System.out.println("tree.equals(hash): " + tree.equals(hash)
+ ", hash.equals(tree): " + hash.equals(tree));
// 2. Entries from firstEntry and floorEntry are read-only snapshots
TreeMap<Integer, String> map = new TreeMap<>(Map.of(1, "one", 5, "five", 9, "nine"));
Map.Entry<Integer, String> first = map.firstEntry();
try {
first.setValue("ONE");
} catch (UnsupportedOperationException e) {
System.out.println("firstEntry().setValue: UnsupportedOperationException");
}
map.put(1, "uno");
System.out.println("snapshot still says " + first.getValue() + ", map says " + map.get(1));
Map.Entry<Integer, String> live = map.entrySet().iterator().next();
live.setValue("ein");
System.out.println("entrySet entry setValue worked: " + map.get(1));
// 3. Natural ordering rejects null keys
try {
map.put(null, "nothing");
} catch (NullPointerException e) {
System.out.println("put(null, ...): NullPointerException");
}
System.out.println("floorKey(0) on keys " + map.keySet() + ": " + map.floorKey(0));
// 4. Changing a key's sort field after insertion hides it from the tree
TreeSet<List<Integer>> boxes = new TreeSet<>((a, b) -> Integer.compare(a.get(0), b.get(0)));
List<Integer> box = new ArrayList<>(List.of(1));
boxes.add(box);
boxes.add(new ArrayList<>(List.of(5)));
boxes.add(new ArrayList<>(List.of(9)));
box.set(0, 20);
System.out.println("after changing 1 to 20: " + boxes + ", contains(box): "
+ boxes.contains(box) + ", first(): " + boxes.first());
// 5. Elements without an order fail on the first add
Set<Object> plain = new TreeSet<>();
try {
plain.add(new Object());
} catch (ClassCastException e) {
System.out.println("adding one Object to a TreeSet: ClassCastException, size "
+ plain.size());
}
}
}
case-insensitive TreeSet: [Apple, Banana], size 2
tree.equals(hash): true, hash.equals(tree): false
firstEntry().setValue: UnsupportedOperationException
snapshot still says one, map says uno
entrySet entry setValue worked: ein
put(null, ...): NullPointerException
floorKey(0) on keys [1, 5, 9]: null
after changing 1 to 20: [[20], [5], [9]], contains(box): false, first(): [20]
adding one Object to a TreeSet: ClassCastException, size 0
- With a case-insensitive comparator, adding
,Apple ,apple andAPPLE left 2 elements. The comparator said the three apples were equal, so the later ones were treated as duplicates and dropped without any error.Banana - Equality became one-sided: the tree set of lowercase names equalled the hash set of capitalised names, but the hash set did not equal the tree set. The
documentation warns that a set whose ordering is not consistent with equals breaks the generalTreeSet contract.Set - The entry from
refusedfirstEntry() and still saidsetValue after the map changed toone . Entries returned by the navigation methods are snapshots. An entry reached throughuno is live, and itsentrySet() changed the map tosetValue .ein threwput(null, ...) , because natural ordering cannot compareNullPointerException . A navigation query with no answer, such asnull here, returnsfloorKey(0) instead.null- Changing a stored list from 1 to 20 left it at the front, printed as
, and[[20], [5], [9]] returned false for the very object in the set. The search went right past 5 and 9 and found nothing. Never change the fields a comparator reads while the element is stored; remove the element, change it, and add it back instead.contains(box) - Adding a single plain
threwObject and left the set empty. The JDK 21 source ofClassCastException compares the first key with itself, commented as a type and null check, so a missing comparator fails at the first insertion rather than waiting for a second element to compare against.TreeMap
Java 21 sequenced views and concurrent navigation
Java 21 (JEP 431) made NavigableMapSequencedMapNavigableSetSequencedSetConcurrentSkipListMap
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.stream.IntStream;
public class SequencedAndConcurrent {
public static void main(String[] args) throws InterruptedException {
// Java 21: TreeMap is also a SequencedMap
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("carol", 71);
scores.put("alice", 92);
scores.put("bob", 85);
NavigableMap<String, Integer> reversed = scores.reversed();
System.out.println("reversed(): " + reversed + ", same as descendingMap(): "
+ reversed.equals(scores.descendingMap()));
System.out.println("sequencedKeySet().reversed(): " + scores.sequencedKeySet().reversed());
try {
scores.putFirst("zed", 1);
} catch (UnsupportedOperationException e) {
System.out.println("putFirst on a TreeMap: UnsupportedOperationException");
}
reversed.put("dave", 60);
System.out.println("put through reversed view: " + scores);
// ConcurrentSkipListMap: the same navigation, safe to share between threads
ConcurrentNavigableMap<Integer, String> slots = new ConcurrentSkipListMap<>();
List<Thread> threads = IntStream.range(0, 4).mapToObj(t -> Thread.ofPlatform().start(() -> {
for (int i = t; i < 10000; i += 4) {
slots.put(i * 10, "thread-" + t);
}
})).toList();
for (Thread th : threads) {
th.join();
}
System.out.println("slots after 4 threads: " + slots.size()
+ ", ceilingKey(12_345): " + slots.ceilingKey(12345)
+ ", headMap(50): " + slots.headMap(50).keySet());
// Unlike a TreeMap, iterating while another thread writes does not throw
Thread writer = Thread.ofPlatform().start(() -> {
for (int i = 0; i < 5000; i++) {
slots.remove(i * 10);
}
});
int seen = 0;
for (Integer k : slots.keySet()) {
seen += k >= 0 ? 1 : 0;
}
writer.join();
System.out.println("iterated " + (seen > 0 ? "without an exception" : "nothing")
+ "; size now " + slots.size());
}
}
reversed(): {carol=71, bob=85, alice=92}, same as descendingMap(): true
sequencedKeySet().reversed(): [carol, bob, alice]
putFirst on a TreeMap: UnsupportedOperationException
put through reversed view: {alice=92, bob=85, carol=71, dave=60}
slots after 4 threads: 10000, ceilingKey(12_345): 12350, headMap(50): [0, 10, 20, 30, 40]
iterated without an exception; size now 5000
printedreversed() and equalled{carol=71, bob=85, alice=92} . On adescendingMap() it returns aTreeMap , so the reversed view still hasNavigableMap ,floorKey and the rest, with the directions swapped.subMap threwputFirst . A sorted map decides positions from the keys, so it cannot honour a request to place a key first; the same applies toUnsupportedOperationException ,putLast andaddFirst on aaddLast .TreeSet- A
through the reversed view still landed in sorted position:put appeared afterdave=60 in the original map.carol - Four threads put 10,000 keys into one
with no locks in the calling code, and none were lost. Navigation worked as on a tree:ConcurrentSkipListMap found 12350 andceilingKey(12345) listed the first five keys.headMap(50) - Iterating the key set while another thread removed 5,000 keys did not throw. Skip list iterators are weakly consistent: they never throw
, but may or may not show changes made during the loop. AConcurrentModificationException shared this way would need external locking.TreeMap
Lookups in a skip list cost O(log n) on average, like a tree, but with more memory per entry. Use ConcurrentSkipListMapTreeMap
When to use navigation
| Question | Use |
|---|---|
| Which band or tier does x fall into? | floorEntry(x) |
| What is the next free slot after x? | ceiling(x)higher(x) |
| Everything between two keys | subMap(from, true, to, true) |
| Everything before or after a key | headMaptailMap |
| Smallest or largest, removing it | pollFirstEntrypollLastEntry |
| Highest first | descendingMap()descendingSet() |
| Only exact lookups | HashMap |
| Sorted and shared between threads | ConcurrentSkipListMap |
How TreeMapLinkedHashMapHashMap