How do you use TreeMap and NavigableMap methods like floorKey, ceilingKey, headMap and subMap?

TreeMap keeps its keys sorted (it is a red-black tree) and implements NavigableMap. That makes it easy to answer range questions such as "the nearest key below X", "all keys between A and B" or "the first and last entries", in O(log n), which a HashMap can't do.

Key Points: • floorKey(x): the greatest key ≤ x. ceilingKey(x): the smallest key ≥ x. lowerKey and higherKey are the strict versions. • headMap(x) gives keys < x, tailMap(x) keys ≥ x, and subMap(a, b) keys from a (inclusive) to b (exclusive). Overloads let you choose inclusive or exclusive bounds. • firstEntry(), lastEntry(), pollFirstEntry() and descendingMap() are also available. • The range methods return views backed by the original map, not copies. • Real uses: tax slabs, price bands, time-based lookups (the version at a given time), leaderboards and scheduling.

Code Example:

import java.util.NavigableMap;
import java.util.TreeMap;

public class TreeMapRanges {

    public static void main(String[] args) {
        // Income tax slab: lower limit -> rate
        NavigableMap<Integer, Integer> slabs = new TreeMap<>();
        slabs.put(0, 0);
        slabs.put(400_000, 5);
        slabs.put(800_000, 10);
        slabs.put(1_200_000, 15);
        slabs.put(1_600_000, 20);

        int income = 950_000;
        System.out.println("Slab for " + income + ": " + slabs.floorEntry(income).getValue() + "%");
        System.out.println("Next slab starts at: " + slabs.higherKey(income));

        System.out.println("Slabs below 8L: " + slabs.headMap(800_000));
        System.out.println("Slabs 4L to 12L: " + slabs.subMap(400_000, true, 1_200_000, true));
        System.out.println("Highest slab: " + slabs.lastEntry());
        System.out.println("Descending keys: " + slabs.descendingKeySet());
    }
}

Output:

Slab for 950000: 10% Next slab starts at: 1200000 Slabs below 8L: {0=0, 400000=5} Slabs 4L to 12L: {400000=5, 800000=10, 1200000=15} Highest slab: 1600000=20 Descending keys: [1600000, 1200000, 800000, 400000, 0]

Good to Know: TreeSet offers the same navigation methods for single values: floor(), ceiling(), headSet(), tailSet() and subSet(). If you need these operations from several threads, use ConcurrentSkipListMap or ConcurrentSkipListSet.

Interview Tip: A concise interview answer is:

"TreeMap is a red-black tree that keeps keys sorted and implements NavigableMap, so I can answer range queries in O(log n): floorKey and ceilingKey find the nearest keys, and headMap, tailMap and subMap return ranges as views. I use it for things like tax slabs, price bands or finding the version valid at a given time, where a HashMap can't help."

Previous question: How does PriorityQueue work, and how do you use it to find the top K elements?

Next question: How do you implement an LRU cache using LinkedHashMap?

More Java Collections interview questions

All Java Collections questions