In Java, TreeMap (in java.util, since Java 1.2) stores key/value pairs sorted by key, like a dictionary or a phone book. put() stores a pair, get() reads a value, and remove() deletes it.
Inside is a red-black tree (a self-balancing binary search tree), so get, put, containsKey, and remove take O(log n) time. It implements NavigableMap (Java 6), SortedMap, Map, Cloneable, and Serializable. The TreeMap Methods index lists every guide.
Two rules to remember.
A TreeMap is not thread-safe: wrap it with Collections.synchronizedSortedMap or use ConcurrentSkipListMap. Its iterators are fail-fast: changing the keys while looping throws ConcurrentModificationException, so remove through the iterator or removeIf.
Syntax
Java Syntax
Import the class, then create a map. Pass a Comparator to change the order:
Java
import java.util.Comparator;
import java.util.NavigableMap;
import java.util.TreeMap;
TreeMap<String, Integer> ages = new TreeMap<>(); // natural order
NavigableMap<Integer, String> desc = new TreeMap<>(Comparator.reverseOrder());
TreeMap<String, Integer> noCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
ages.put("Lina", 29); // 29 is autoboxed to Integer
Integer b = ages.get("Omar"); // null (no such key)
Declare the variable as TreeMap or NavigableMap (not just Map) to reach navigation methods such as floorKey().
Reference
How Keys Are Ordered
Each key is placed by comparing it with the keys already in the tree: by its own compareTo (natural ordering) or by the map's Comparator. comparator() tells you which.
Rule
What it means for you
Natural ordering
Integer keys sort numerically; String keys by character code, so "Zoe" comes before "adam".
Comparator-based key equality
Keys are the same key when compare returns 0: with String.CASE_INSENSITIVE_ORDER, "Anna" and "anna" share one entry, and the first key object is kept.
Null rules
A null key throws NullPointerException with natural ordering; null values are fine.
Comparable keys
Keys that are not Comparable (and no comparator) throw ClassCastException, even on the first put.
Reference
Navigation Methods and Live Views
Sorted keys make "nearest key" questions and partial views cheap:
Entries from navigation methods are read-only snapshots (setValue throws UnsupportedOperationException). Views are live: changes flow both ways, and putting a key outside a view's range throws IllegalArgumentException. Entries met while looping over entrySet() do allow setValue.
Reference
TreeMap vs HashMap, LinkedHashMap, and Others
All implement Map; they differ in order, speed, and null rules:
Class
Order
Keep in mind
TreeMap
Sorted by key
O(log n) operations; navigation and range views; no null key with natural ordering
Usually the fastest map (constant time on average); one null key allowed
LinkedHashMap
Insertion order (or access order)
A HashMap with a linked list through the entries; supports putFirst/putLast in Java 21
Java 21:TreeMap is a SequencedMap, but since the tree decides where keys go, putFirst() and putLast() always throw UnsupportedOperationException; reversed() returns descendingMap().
Code
Java Examples
Example 1 — A Class Roster Sorted by Roll Number
Add four pupils in random order, read one, remove one, and loop over the rest; the keys stay sorted.
Java
import java.util.Map;
import java.util.TreeMap;
public class TreeMapBasics {
public static void main(String[] args) {
TreeMap<Integer, String> roster = new TreeMap<>();
roster.put(17, "Nadia");
roster.put(3, "Tomas");
roster.put(42, "Wen");
roster.put(8, "Priya");
System.out.println(roster);
System.out.println("roll 42: " + roster.get(42));
roster.remove(3);
System.out.println("first roll now: " + roster.firstKey() + ", last: " + roster.lastKey());
for (Map.Entry<Integer, String> e : roster.entrySet()) {
System.out.println(e.getKey() + ". " + e.getValue());
}
}
}
Output
{3=Tomas, 8=Priya, 17=Nadia, 42=Wen}
roll 42: Wen
first roll now: 8, last: 42
8. Priya
17. Nadia
42. Wen
How It Works
Numbers sort as numbers. The rolls went in as 17, 3, 42, 8, yet the map prints 3, 8, 17, 42, because Integer keys use numeric natural ordering.
Ends move with the data. After roll 3 is removed, firstKey() is 8 while lastKey() stays 42.
A loop in key order.entrySet() walks the remaining pupils from the smallest roll number to the largest, giving a ready-made class list.
Example 2 — Find the Last and the Next Train
Zero-padded times sort as text in time order, so navigation methods answer "before" and "after" directly.
Java
import java.util.TreeMap;
public class TreeMapNavigationTour {
public static void main(String[] args) {
TreeMap<String, String> departures = new TreeMap<>();
departures.put("07:15", "Leeds");
departures.put("08:40", "York");
departures.put("09:05", "Hull");
departures.put("10:30", "Derby");
String now = "08:50";
System.out.println("last train gone: " + departures.floorEntry(now));
System.out.println("next train: " + departures.ceilingEntry(now));
System.out.println("already left: " + departures.headMap(now).keySet());
System.out.println("still to come: " + departures.tailMap(now).keySet());
}
}
Output
last train gone: 08:40=York
next train: 09:05=Hull
already left: [07:15, 08:40]
still to come: [09:05, 10:30]
How It Works
No exact match needed. 08:50 is not a key, yet floorEntry returns the closest earlier departure (08:40 York) and ceilingEntry the closest later one (09:05 Hull).
Split at a point in time.headMap(now) holds the times before 08:50 and tailMap(now) those from 08:50 on, without copying anything.
Why zero-padding matters. "07:15" sorts before "10:30" only because every hour has two digits; "7:15" would sort after "10:30" as text.
Example 3 — Reverse Order and Case-Insensitive Keys
A leaderboard sorted from high to low, and the same names counted with and without case sensitivity.
Java
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapOrderingRules {
public static void main(String[] args) {
TreeMap<Integer, String> leaderboard = new TreeMap<>(Comparator.reverseOrder());
leaderboard.put(870, "Ola");
leaderboard.put(1250, "Ken");
leaderboard.put(990, "Bea");
System.out.println("high to low: " + leaderboard);
TreeMap<String, Integer> natural = new TreeMap<>();
TreeMap<String, Integer> noCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
String[] names = {"bob", "Alice", "alice", "Carl"};
for (String n : names) {
natural.merge(n, 1, Integer::sum);
noCase.merge(n, 1, Integer::sum);
}
System.out.println("natural: " + natural);
System.out.println("ignore case: " + noCase);
}
}
Output
high to low: {1250=Ken, 990=Bea, 870=Ola}
natural: {Alice=1, Carl=1, alice=1, bob=1}
ignore case: {Alice=2, bob=1, Carl=1}
How It Works
Reverse comparator, reverse map.Comparator.reverseOrder() flips the numeric order, so the top score 1250 is printed first.
Capitals first by default. Natural String order compares character codes, and every uppercase letter comes before every lowercase one, giving Alice, Carl, alice, bob.
One key for two spellings. With CASE_INSENSITIVE_ORDER, "alice" equals "Alice", so the counts merge into Alice=2 and the names sort A, b, C regardless of case.
A java.util class that stores key/value pairs sorted by key in a red-black tree, so get, put, containsKey, and remove take O(log n) time. It implements NavigableMap, SortedMap, and Map.
By the keys' natural ordering (compareTo) or by a Comparator passed to the constructor. Two keys that compare as 0 are the same key, even if equals() says they differ.
Null values are fine. A null key throws NullPointerException with natural ordering; only a Comparator that handles null can accept one.
No. Wrap it with Collections.synchronizedSortedMap(...) and synchronize on the wrapper while iterating, or use ConcurrentSkipListMap.
When you need keys in sorted order or nearest-key and range questions such as "the largest key at most 84". Otherwise HashMap is usually faster.