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

TreeMap and TreeSet keep their keys in a red-black tree, a balanced binary search tree ordered by the keys' natural order or a comparator. Because every key has a known position in the order, the tree can answer "which key is closest to x?" by walking from the root to where x would be, in O(log n) steps. NavigableMap and NavigableSet, added in Java 6, are the interfaces that expose these queries.

The navigation methods return null when there is no such key, while first and last throw NoSuchElementException on an empty collection. Range methods return views, not copies: they reflect and write through to the original.

Navigation methods (map versions in brackets)
MethodReturnsBest for
floor(x) [floorKey, floorEntry]Largest key ≤ xBands, versions in effect at a time
ceiling(x) [ceilingKey, ceilingEntry]Smallest key ≥ xNext available slot
lower(x), higher(x)Strictly below or above xPrevious and next neighbours
first(), last(), pollFirst(), pollLast()The ends; poll also removesSmallest or largest; simple queues
subSet, headSet, tailSet [subMap, headMap, tailMap]A range viewTime windows, alphabetical ranges
descendingSet() [descendingMap()]A reverse-order viewNewest first, highest first

ConcurrentSkipListMap and ConcurrentSkipListSet implement the same interfaces for concurrent use. The examples on this page were run with JDK 21.

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.

Java
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:

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]
  • floor(100) found 90, the latest slot at or before 100, and ceiling(100) found 120, the earliest at or after it.
  • lower and higher exclude the value itself: lower(90) is 30 even though 90 is in the set.
  • ceiling(300) returned null, so check results before unboxing them into an int.
  • descendingSet() reverses the order, and pollFirst() removed and returned the earliest slot, booking it.

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.

Java
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:

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
  • floorEntry(amount) 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.
  • The same pattern fits tax brackets, grading scales, discount tiers and "which configuration version was active at time t". A chain of if statements does the same work but is harder to change.
  • Include a band starting at the smallest possible value, here 0, so that floorEntry never returns 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.

Java
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:

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]
  • subMap(3, true, 10, true) includes both ends. The two-argument forms follow the half-open convention: headMap(7) excludes 7 and tailMap(14) includes 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. floorEntry(12) found day 10, and descendingKeySet() lists the days newest first.

Sets with a comparator, and what sorting costs

A TreeSet with a case-insensitive comparator shows set ranges and polling. The second half compares a million lookups in a TreeMap and a HashMap of a million keys, keeping the fastest of three runs.

Java
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):

Output
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, Apple and Kiwi sort among the lowercase words. subSet("b", "c") includes b and excludes c, so it holds only banana; the four-argument version can include both ends.
  • descendingSet() is a reverse view of the same set, and pollFirst and pollLast removed the two ends.
  • A TreeMap.get took from several to more than twenty times as long as HashMap.get across runs: each lookup follows about 20 tree links through scattered memory instead of one hash bucket.
  • floorKey costs the same as get, and a HashMap 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.

Traps: comparators, snapshots, nulls and changing keys

A tree map or set finds elements only by comparing them, never by calling equals or hashCode. Most of the surprises with these classes follow from that. The program shows five of them running.

Java
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());
        }
    }
}
Output
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, APPLE and Banana left 2 elements. The comparator said the three apples were equal, so the later ones were treated as duplicates and dropped without any error.
  • 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 TreeSet documentation warns that a set whose ordering is not consistent with equals breaks the general Set contract.
  • The entry from firstEntry() refused setValue and still said one after the map changed to uno. Entries returned by the navigation methods are snapshots. An entry reached through entrySet() is live, and its setValue changed the map to ein.
  • put(null, ...) threw NullPointerException, because natural ordering cannot compare null. A navigation query with no answer, such as floorKey(0) here, returns null instead.
  • Changing a stored list from 1 to 20 left it at the front, printed as [[20], [5], [9]], and contains(box) 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.
  • Adding a single plain Object threw ClassCastException and left the set empty. The JDK 21 source of TreeMap 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.

Java 21 sequenced views and concurrent navigation

Java 21 (JEP 431) made NavigableMap extend SequencedMap and NavigableSet extend SequencedSet. The new methods mostly give existing behaviour common names, and a few refuse to work on a sorted collection. For several threads, ConcurrentSkipListMap offers the same navigation methods with lock-free reads.

Java
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());
    }
}
Output
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
  • reversed() printed {carol=71, bob=85, alice=92} and equalled descendingMap(). On a TreeMap it returns a NavigableMap, so the reversed view still has floorKey, subMap and the rest, with the directions swapped.
  • putFirst threw UnsupportedOperationException. A sorted map decides positions from the keys, so it cannot honour a request to place a key first; the same applies to putLast, addFirst and addLast on a TreeSet.
  • A put through the reversed view still landed in sorted position: dave=60 appeared after carol in the original map.
  • Four threads put 10,000 keys into one ConcurrentSkipListMap with no locks in the calling code, and none were lost. Navigation worked as on a tree: ceilingKey(12345) found 12350 and headMap(50) listed the first five keys.
  • Iterating the key set while another thread removed 5,000 keys did not throw. Skip list iterators are weakly consistent: they never throw ConcurrentModificationException, but may or may not show changes made during the loop. A TreeMap shared this way would need external locking.

Lookups in a skip list cost O(log n) on average, like a tree, but with more memory per entry. Use ConcurrentSkipListMap only when the map really is shared; a TreeMap is lighter for single-threaded code. Background on the sequenced interfaces is on the TreeMap and LinkedHashMap page.

When to use navigation

Choosing a navigation method
QuestionUse
Which band or tier does x fall into?floorEntry(x)
What is the next free slot after x?ceiling(x), or higher(x) to exclude x
Everything between two keyssubMap(from, true, to, true)
Everything before or after a keyheadMap, tailMap
Smallest or largest, removing itpollFirstEntry, pollLastEntry
Highest firstdescendingMap() or descendingSet()
Only exact lookupsHashMap, which is faster
Sorted and shared between threadsConcurrentSkipListMap

How TreeMap compares with LinkedHashMap and HashMap in general is covered on TreeMap and LinkedHashMap.