TreeMap navigation methods
Answer nearest-key and range questions without scanning the whole map.
Open this lesson in the learning hubKey points
TreeMapandTreeSetare sorted, so they can answer questions a hash table cannot.- Nearest key:
floorKeyis the largest key not above yours,ceilingKeythe smallest not below. lowerKeyandhigherKeyare the same idea but strict — they never return your own key.- Ranges come back as live views:
headMap,tailMap,subMap. Writing to a view writes to the map. - Ends:
firstEntry,lastEntry, pluspollFirstEntryandpollLastEntrywhich also remove. - Perfect for lookup tables — grade bands, price tiers, time buckets. Lookups and range queries are O(log n).
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
System.out.println("map : " + grades);
System.out.println("floorEntry(85) : " + grades.floorEntry(85) + " (largest key <= 85)");
System.out.println("ceilingKey(85) : " + grades.ceilingKey(85) + " (smallest key >= 85)");
System.out.println("lowerKey(80) : " + grades.lowerKey(80) + " (strictly less)");
System.out.println("higherKey(80) : " + grades.higherKey(80) + " (strictly greater)");
System.out.println("firstKey/lastKey : " + grades.firstKey() + " / " + grades.lastKey());
System.out.println("headMap(80) : " + grades.headMap(80));
System.out.println("tailMap(80) : " + grades.tailMap(80));
System.out.println("subMap(70, 90) : " + grades.subMap(70, 90));
System.out.println("descendingMap : " + grades.descendingMap());
System.out.println("pollFirstEntry : " + grades.pollFirstEntry() + " leaves " + grades);
TreeSet<String> words = new TreeSet<>(List.of("apple", "fig", "kiwi", "pear"));
System.out.println("ceiling(grape) : " + words.ceiling("grape"));
System.out.println("headSet(kiwi) : " + words.headSet("kiwi"));
System.out.println("descendingSet : " + words.descendingSet());
}
}
When the question is "nearest" or "between", only a sorted map can answer it cheaply.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.