Java TreeMap headMap() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

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.

Java
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
CallWhat 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
// java.util.TreeMap<K, V>
public SortedMap<K, V> headMap(K toKey)

public NavigableMap<K, V> headMap(K toKey, boolean inclusive)   // Java 6

Parameters

ParameterDescription
toKey (K)Upper bound of the view.
inclusive (boolean)Two-argument form only: true to include toKey.

Return Value

Return ValueDescription
SortedMap<K, V>One-argument form: live view of keys strictly below toKey.
NavigableMap<K, V>Two-argument form: live view with navigation methods.

Compare with Similar Methods

Range views compared:

MethodHow it differs
tailMap(k)The complementary upper part, from k inclusive.
subMap(a, b)A range with both a lower and an upper bound.
lowerKey(k)Only the nearest key below k.
pollFirstEntry()Remove from the low end one entry at a time.

Java Examples

Example 1 — Gifts Within a Budget

Prices are keys; headMap lists everything cheaper than the budget.

Java
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());
    }
}

How It Works

  1. Sorted and filtered at once. The three gifts below 50 come out cheapest first, without any loop or sort call.
  2. Exclusive by default. The lamp costs exactly 60, and headMap(60) leaves it out because its keys must be strictly less than 60.
  3. 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.

Java
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());
    }
}

How It Works

  1. Preview before deleting. Printing the view's key set first shows exactly which two dates fall before the cutoff.
  2. 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.
  3. 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.

Java
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());
        }
    }
}

How It Works

  1. Navigation needs the second form. SortedMap has no lastEntry(); the NavigableMap returned by headMap(2, true) does, and reports 2=Gym.
  2. Keys below the bound are welcome. Floor -1 is under 2, so low.put(-1, ...) succeeds and the parking level appears in floors.
  3. The bound itself is outside. low covers keys below 2 only, so even replacing floor 2 through it throws IllegalArgumentException.

Frequently Asked Questions

Not by default: headMap(k) contains keys strictly less than k. Use headMap(k, true) to include k.
No. It is a live view backed by the map; changes in either one are visible in the other.
Call map.headMap(value).clear(). It removes those entries from the original map.
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.
headMap(k) returns SortedMap; headMap(k, inclusive) returns NavigableMap, which adds methods like floorKey and lastEntry.

Next: higherEntry()

Get the pair with the next key strictly above a value.

higherEntry() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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