Java TreeMap subMap() Method

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

Definition

In Java, subMap(fromKey, toKey) returns the part of a TreeMap whose keys lie from fromKey (inclusive) up to toKey (exclusive). The four-argument form, added in Java 6, lets you choose whether each end is inclusive.

The result is a live view, not a copy: it shares storage with the map, so changes on either side are visible in the other, and creating it costs only O(log n) per lookup. The two-argument form returns SortedMap; the four-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

Give the lower and upper bound; optionally say whether each is included.

Java
TreeMap<Integer, Integer> sales = new TreeMap<>();
SortedMap<Integer, Integer> a = sales.subMap(3, 7);                 // keys 3 <= k < 7
NavigableMap<Integer, Integer> b = sales.subMap(3, true, 7, true);  // keys 3 <= k <= 7
CallWhat it does
map.subMap(from, to)Keys in [from, to): from included, to excluded.
map.subMap(from, true, to, true)Keys in [from, to]: both ends included.
map.subMap(from, false, to, false)Keys strictly between the two bounds.

For String keys, subMap("A", "N") is a neat way to get every key that starts with A to M: any word beginning with N sorts after the one-letter string "N".

Library declarations
Java
// java.util.TreeMap<K, V>
public SortedMap<K, V> subMap(K fromKey, K toKey)

public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive,
                                 K toKey, boolean toInclusive)   // Java 6

Parameters

ParameterDescription
fromKey (K)Low end of the range; included unless fromInclusive is false.
toKey (K)High end of the range; excluded unless toInclusive is true.
fromInclusive, toInclusive (boolean)Four-argument form only: whether each bound belongs to the view.

Return Value

Return ValueDescription
SortedMap<K, V>Two-argument form: a live view of the half-open range.
NavigableMap<K, V>Four-argument form: a live view with navigation methods.

Compare with Similar Methods

The range views side by side:

MethodHow it differs
headMap(to)Everything below to.
tailMap(from)Everything from from upward.
descendingMap()The whole map in reverse order.
Collections.unmodifiableSortedMap()Wrap a view to make it read-only.

Java Examples

Example 1 — Contacts From A to M

subMap("A", "N") picks every name starting with A through M.

Java
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapSubMapAToM {
    public static void main(String[] args) {
        TreeMap<String, Integer> contacts = new TreeMap<>();
        contacts.put("Mona", 240);
        contacts.put("Alba", 201);
        contacts.put("Zara", 377);
        contacts.put("Kofi", 118);
        contacts.put("Nils", 402);
        contacts.put("Bea", 315);

        SortedMap<String, Integer> firstHalf = contacts.subMap("A", "N");
        System.out.println("A to M: " + firstHalf);
        System.out.println("first: " + firstHalf.firstKey() + ", last: " + firstHalf.lastKey());
        System.out.println("names in range: " + firstHalf.size() + " of " + contacts.size());
    }
}

How It Works

  1. An upper bound that is not a name. "N" is not in the map, yet it works as a fence: "Mona" sorts before it while "Nils" sorts after it, because a longer string with the same first letter is greater.
  2. The view has its own ends. firstKey() and lastKey() on the view report Alba and Mona, the ends of the range rather than of the whole map.
  3. Counting is range-aware. size() on the view gives 4 out of the 6 contacts; Nils and Zara lie outside.

Example 2 — Half-Open, Closed, and Open Ranges

Units sold per day, viewed through three versions of "days 3 to 7".

Java
import java.util.TreeMap;

public class TreeMapSubMapBounds {
    public static void main(String[] args) {
        TreeMap<Integer, Integer> sales = new TreeMap<>();
        sales.put(1, 5);
        sales.put(3, 8);
        sales.put(5, 2);
        sales.put(7, 9);
        sales.put(9, 4);

        System.out.println("[3, 7): " + sales.subMap(3, 7));
        System.out.println("[3, 7]: " + sales.subMap(3, true, 7, true));
        System.out.println("(3, 7): " + sales.subMap(3, false, 7, false));
    }
}

How It Works

  1. The default is half-open. The two-argument call includes day 3 but stops before day 7, matching the usual from-inclusive, to-exclusive convention.
  2. Closing the top end. Passing true for toInclusive adds day 7 with its 9 units.
  3. Opening both ends. With both flags false, only the keys strictly between 3 and 7 remain, which here is day 5.

Example 3 — A Window That Follows the Map

Changes flow both ways between the map and the view, but the view only accepts keys inside its range.

Java
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapSubMapLive {
    public static void main(String[] args) {
        TreeMap<Integer, String> seats = new TreeMap<>();
        seats.put(10, "Ann");
        seats.put(25, "Bo");
        seats.put(40, "Cy");

        SortedMap<Integer, String> middle = seats.subMap(20, 30);
        System.out.println("middle: " + middle);
        seats.put(22, "Dev");
        System.out.println("after seats.put(22): " + middle);
        middle.remove(25);
        System.out.println("after middle.remove(25): " + seats);
        try {
            middle.put(35, "Eve");
        } catch (IllegalArgumentException e) {
            System.out.println("middle.put(35): " + e.getClass().getSimpleName());
        }
        try {
            seats.subMap(30, 20);
        } catch (IllegalArgumentException e) {
            System.out.println("subMap(30, 20): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Map to view. Seat 22 was added to seats after the view was created, and it appears in middle because 22 lies in [20, 30).
  2. View to map. Removing 25 through the view deletes Bo from the real map; the view stores nothing of its own.
  3. Two kinds of out of range. Seat 35 is outside the window, so middle.put is rejected, and subMap(30, 20) fails because its lower bound is above its upper bound.

Frequently Asked Questions

Not in the two-argument form: subMap(from, to) includes from and excludes to. Use subMap(from, true, to, true) to include both ends.
No. It returns a live view backed by the map. Wrap it in new TreeMap<>(view) if you need an independent copy.
Either fromKey is greater than toKey, or you tried to put a key outside the view's range.
subMap(from, to) returns SortedMap with fixed bounds; subMap(from, fromInclusive, to, toInclusive) returns NavigableMap and lets you choose each bound.
Yes. map.subMap(a, b).clear() removes every key in [a, b) from the backing map.

Next: tailMap()

A live view of the keys from a starting key upward.

tailMap() 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.

13 people found this page helpful