Home Java TreeMap Methods headMap() Java TreeMap headMap() Method Definition In Java, headMap(toKey) returns the part of a TreeMap whose keys are strictly less than toKey. The overload headMap(toKey, inclusive), added in Java 6, can also include toKey itself.
Like every range method, it returns a live view: entries added to or removed from the map show up in the view, and the view writes through to the map. The one-argument form returns SortedMap; the two-argument form returns NavigableMap.
An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe .
Syntax Pass the upper bound; add true to include it.
TreeMap<Integer, String> items = new TreeMap<>();
SortedMap<Integer, String> cheap = items.headMap(50); // keys < 50
NavigableMap<Integer, String> upTo = items.headMap(60, true); // keys <= 60 Call What it does map.headMap(k)Keys < k (exclusive). map.headMap(k, true)Keys ≤ k (inclusive). map.headMap(k).clear()Deletes every key below k from the map.
The bound does not need to be a key in the map. Any value of the key type works, which makes headMap(cutoff) handy for "everything before this date" questions.
Library declarations // java.util.TreeMap<K, V>
public SortedMap<K, V> headMap(K toKey)
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) // Java 6 Parameters Parameter Description toKey (K)Upper bound of the view. inclusive (boolean)Two-argument form only: true to include toKey.
Return Value Return Value Description SortedMap<K, V>One-argument form: live view of keys strictly below toKey. NavigableMap<K, V>Two-argument form: live view with navigation methods.
Important
Putting a key at or above the bound through the view throws IllegalArgumentException (for headMap(k), k itself is already outside). On a range view, a bound outside that view's range also throws it. A null bound throws NullPointerException with natural ordering.
Compare with Similar Methods Range views compared:
Java Examples 1. Below a price 2. Bulk removal 3. Return types and range checks Example 1 — Gifts Within a Budget Prices are keys; headMap lists everything cheaper than the budget.
import java.util.TreeMap;
public class TreeMapHeadMapBudget {
public static void main(String[] args) {
TreeMap<Integer, String> gifts = new TreeMap<>();
gifts.put(40, "Book");
gifts.put(99, "Headphones");
gifts.put(15, "Socks");
gifts.put(60, "Lamp");
gifts.put(25, "Mug");
System.out.println("under 50: " + gifts.headMap(50));
System.out.println("under 60: " + gifts.headMap(60).keySet());
System.out.println("up to 60: " + gifts.headMap(60, true).keySet());
}
} under 50: {15=Socks, 25=Mug, 40=Book}
under 60: [15, 25, 40]
up to 60: [15, 25, 40, 60] How It Works Sorted and filtered at once. The three gifts below 50 come out cheapest first, without any loop or sort call.Exclusive by default. The lamp costs exactly 60, and headMap(60) leaves it out because its keys must be strictly less than 60.Inclusive on request. headMap(60, true) adds the lamp; its keySet() shows the four prices that fit.Example 2 — Delete Log Entries Older Than a Date headMap(cutoff).clear() removes every older entry from the real map in one statement.
import java.util.TreeMap;
public class TreeMapHeadMapPurge {
public static void main(String[] args) {
TreeMap<String, String> logs = new TreeMap<>();
logs.put("2026-11-01", "boot");
logs.put("2026-11-09", "update");
logs.put("2026-11-15", "crash");
logs.put("2026-11-18", "patch");
String cutoff = "2026-11-10";
System.out.println("removing: " + logs.headMap(cutoff).keySet());
logs.headMap(cutoff).clear();
System.out.println("kept: " + logs);
System.out.println("oldest now: " + logs.firstKey());
}
} removing: [2026-11-01, 2026-11-09]
kept: {2026-11-15=crash, 2026-11-18=patch}
oldest now: 2026-11-15 How It Works Preview before deleting. Printing the view's key set first shows exactly which two dates fall before the cutoff.Clearing a view clears the map. clear() on the head view deletes those entries from logs itself, leaving only the dates from 2026-11-10 onward.The new low end. After the purge, firstKey() on the map reports 2026-11-15, the oldest log still kept.Example 3 — SortedMap, NavigableMap, and an Out-of-Range put() The two overloads return different types, and a head view refuses keys at or above its bound.
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
public class TreeMapHeadMapTypes {
public static void main(String[] args) {
TreeMap<Integer, String> floors = new TreeMap<>();
floors.put(0, "Lobby");
floors.put(1, "Cafe");
floors.put(2, "Gym");
floors.put(5, "Roof");
SortedMap<Integer, String> low = floors.headMap(2);
NavigableMap<Integer, String> lowNav = floors.headMap(2, true);
System.out.println("headMap(2): " + low);
System.out.println("headMap(2, true).lastEntry(): " + lowNav.lastEntry());
low.put(-1, "Parking");
System.out.println("after low.put(-1): " + floors);
try {
low.put(2, "Pool");
} catch (IllegalArgumentException e) {
System.out.println("low.put(2): " + e.getClass().getSimpleName());
}
}
} headMap(2): {0=Lobby, 1=Cafe}
headMap(2, true).lastEntry(): 2=Gym
after low.put(-1): {-1=Parking, 0=Lobby, 1=Cafe, 2=Gym, 5=Roof}
low.put(2): IllegalArgumentException How It Works Navigation needs the second form. SortedMap has no lastEntry(); the NavigableMap returned by headMap(2, true) does, and reports 2=Gym.Keys below the bound are welcome. Floor -1 is under 2, so low.put(-1, ...) succeeds and the parking level appears in floors.The bound itself is outside. low covers keys below 2 only, so even replacing floor 2 through it throws IllegalArgumentException.Frequently Asked Questions Does TreeMap headMap() include the given key? Not by default: headMap(k) contains keys strictly less than k. Use headMap(k, true) to include k.
Is headMap() a copy? No. It is a live view backed by the map; changes in either one are visible in the other.
How do I delete all keys below a value? Call map.headMap(value).clear(). It removes those entries from the original map.
Why does put() on a headMap view throw IllegalArgumentException? The key is at or above the view's upper bound (or above it, for the inclusive form), so it does not belong to the view.
What type does headMap() return? headMap(k) returns SortedMap; headMap(k, inclusive) returns NavigableMap, which adds methods like floorKey and lastEntry.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful
Helpful Share Copy link Suggestion