TreeMap: Sorted Key-Value Pairs
Use TreeMap to maintain sorted order and navigate with firstKey, lastKey, floorKey, and ceilingKey.
TreeMap: Sorted Key-Value Pairs is a free Java Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, and your progress syncs across the web and the CoddyKit app. The Java Academy course includes 4 lessons in total.
What is TreeMap?
TreeMap is a sorted map implementation backed by a Red-Black tree. Keys are maintained in ascending natural order (or custom comparator order). All basic operations are O(log n).
import java.util.TreeMap;
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Charlie", 85);
scores.put("Alice", 92);
scores.put("Bob", 78);
// Iteration is in key order: Alice, Bob, Charlie
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}firstKey, lastKey, floorKey, ceilingKey
TreeMap's NavigableMap interface exposes navigation methods for finding keys relative to a given value:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "ten"); map.put(20, "twenty"); map.put(30, "thirty"); map.put(40, "forty");
System.out.println(map.firstKey()); // 10
System.out.println(map.lastKey()); // 40
System.out.println(map.floorKey(25)); // 20 (largest key ≤ 25)
System.out.println(map.ceilingKey(25)); // 30 (smallest key ≥ 25)
System.out.println(map.lowerKey(20)); // 10 (strictly less)
System.out.println(map.higherKey(20)); // 30 (strictly greater)Navigating Entries
floorEntry, ceilingEntry, firstEntry, lastEntry return the full Map.Entry rather than just the key:
TreeMap<Integer, String> prices = new TreeMap<>();
prices.put(100, "Budget"); prices.put(300, "Standard"); prices.put(700, "Premium");
var entry = prices.floorEntry(350);
System.out.println(entry.getKey() + ": " + entry.getValue()); // 300: Standard
var top = prices.lastEntry();
System.out.println(top.getValue()); // PremiumsubMap, headMap, tailMap
Extract range views from a TreeMap. These views are backed by the original map — changes in one reflect in the other.
TreeMap<Integer, String> map = new TreeMap<>();
for (int i = 1; i <= 10; i++) map.put(i, "v"+i);
// Keys from 3 (inclusive) to 7 (exclusive)
System.out.println(map.subMap(3, 7)); // {3=v3, 4=v4, 5=v5, 6=v6}
// Keys strictly less than 5
System.out.println(map.headMap(5)); // {1=v1, 2=v2, 3=v3, 4=v4}
// Keys >= 7
System.out.println(map.tailMap(7)); // {7=v7, 8=v8, 9=v9, 10=v10}Inclusive/Exclusive Boundaries
Use the overloaded variants for fine-grained boundary control:
TreeMap<Integer, String> map = new TreeMap<>();
for (int i = 1; i <= 10; i++) map.put(i*10, "v"+i);
// From 30 (inclusive) to 60 (inclusive)
System.out.println(map.subMap(30, true, 60, true));
// {30=v3, 40=v4, 50=v5, 60=v6}descending Order
Use descendingMap() or descendingKeySet() to iterate keys in reverse order:
TreeMap<String, Integer> tm = new TreeMap<>();
tm.put("A", 1); tm.put("C", 3); tm.put("B", 2);
for (String key : tm.descendingKeySet()) {
System.out.print(key + " "); // C B A
}pollFirstEntry and pollLastEntry
Remove and return the first or last entry atomically — useful for building priority maps:
TreeMap<Integer, String> events = new TreeMap<>();
events.put(8, "Breakfast");
events.put(12, "Lunch");
events.put(18, "Dinner");
var first = events.pollFirstEntry(); // removes 8=Breakfast
System.out.println(first.getValue() + " removed");
System.out.println(events.firstKey()); // 12Use Case: Leaderboard
A leaderboard needs players sorted by score. TreeMap sorts by key automatically:
TreeMap<Integer, String> leaderboard = new TreeMap<>(Comparator.reverseOrder());
leaderboard.put(1200, "Alice");
leaderboard.put(1500, "Bob");
leaderboard.put(900, "Carol");
int rank = 1;
for (var e : leaderboard.entrySet()) {
System.out.println(rank++ + ". " + e.getValue() + " (" + e.getKey() + ")");
}
// 1. Bob (1500)
// 2. Alice (1200)
// 3. Carol (900)Use Case: Event Scheduler
Map timestamps to events — use ceilingEntry to find the next scheduled event after a given time:
import java.time.LocalTime;
TreeMap<LocalTime, String> schedule = new TreeMap<>();
schedule.put(LocalTime.of(9,0), "Standup");
schedule.put(LocalTime.of(14,0), "Review");
schedule.put(LocalTime.of(17,0), "Retro");
LocalTime now = LocalTime.of(11, 30);
var next = schedule.ceilingEntry(now);
System.out.println("Next: " + next.getValue()); // ReviewTreeMap vs HashMap Performance
Key comparison:
- HashMap: O(1) average get/put; unordered
- TreeMap: O(log n) get/put; sorted by key
- LinkedHashMap: O(1) average; insertion-ordered
Use TreeMap when you need sorted keys or range queries. HashMap is faster for simple key lookup.
Thread Safety
TreeMap is NOT thread-safe. For concurrent access, use ConcurrentSkipListMap which also maintains sorted order with O(log n) operations and supports concurrent reads/writes.
Quick Check
You have a TreeMap<Integer, String> with keys {10, 20, 30, 40}. What does map.floorKey(25) return?
Recap: TreeMap
Key takeaways:
- TreeMap maintains keys in sorted (ascending) order via Red-Black tree
- All operations are O(log n)
- Navigation: firstKey, lastKey, floorKey, ceilingKey, lowerKey, higherKey
- Range views: subMap, headMap, tailMap (backed views)
- Use ConcurrentSkipListMap for thread-safe sorted maps
Learn Java with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 104
- Lessons
- 374
Frequently Asked Questions
Is the “TreeMap: Sorted Key-Value Pairs” lesson free?
Yes — the full text of “TreeMap: Sorted Key-Value Pairs” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO. The Java Academy course includes 4 lessons in total.
What will I learn in “TreeMap: Sorted Key-Value Pairs”?
Use TreeMap to maintain sorted order and navigate with firstKey, lastKey, floorKey, and ceilingKey. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “TreeMap: Sorted Key-Value Pairs” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- TreeMap: Sorted Key-Value Pairs
- Submaps and Range Views
- TreeSet and NavigableSet
- Custom Ordering in Tree Collections