Java TreeSet subSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, subSet() returns a live view of elements falling between fromElement and toElement.

Two-arg subSet(from, to) includes from and excludes to (SortedSet). Four-arg subSet(from, fromInc, to, toInc) controls both bounds (NavigableSet).

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe. The two-argument form dates back to Java 1.2 (SortedSet); the four-argument form with inclusive flags was added in Java 6 (NavigableSet).

Syntax

Pick the two-argument half-open range or the four-argument overload for explicit bounds.

Java
NavigableSet<Integer> prices = new TreeSet<>(Arrays.asList(10, 20, 35, 50, 75));
SortedSet<Integer> halfOpen = prices.subSet(20, 50);              // [20, 35]
NavigableSet<Integer> closed = prices.subSet(20, true, 50, true); // [20, 35, 50]
CallWhat it does
set.subSet(from, to)Range from from (inclusive) up to to (exclusive).
set.subSet(from, true, to, true)Includes both endpoints.
set.subSet(a, b).clear()Removes every element in [a, b) from the original set.
new TreeSet<>(set.subSet(a, b))Creates an independent snapshot copy of that range.

Bounds do not have to exist inside the set: subSet(15, 45) works fine on [10, 20, 35, 50] and views [20, 35].

Library declarations
Java
// java.util.TreeSet<E>
public SortedSet<E> subSet(E fromElement, E toElement)
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                              E toElement, boolean toInclusive)

// Declared in SortedSet<E> and NavigableSet<E>

Parameters

ParameterDescription
fromElement (E)Lower endpoint of the returned range view.
fromInclusive (boolean)Four-argument overload: true to include fromElement.
toElement (E)Upper endpoint of the returned range view.
toInclusive (boolean)Four-argument overload: true to include toElement.

Return Value

Return ValueDescription
SortedSet<E> / NavigableSet<E>A live view backed by the original TreeSet.

Compare with Similar Methods

All range and reversed views on TreeSet:

MethodHow it differs
headSet(to)Slices everything from the start up to an upper bound.
tailSet(from)Slices everything from a lower bound to the end.
descendingSet()Reverses the whole set in a live view.
ArrayList.subList(i, j)Slices a list by integer indexes rather than sorted element bounds.

Java Examples

Example 1 — Filter Products Within a Price Bracket

Compare the default half-open subSet(20, 50) against the inclusive subSet(20, true, 50, true), plus a snapshot copy.

Java
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;

public class TreeSetSubSetPrices {
    public static void main(String[] args) {
        NavigableSet<Integer> prices = new TreeSet<>(Arrays.asList(10, 20, 35, 50, 75));

        SortedSet<Integer> mid = prices.subSet(20, 50);
        NavigableSet<Integer> inclusive = prices.subSet(20, true, 50, true);
        TreeSet<Integer> snapshot = new TreeSet<>(mid);

        System.out.println("half-open [20, 50): " + mid);
        System.out.println("closed [20, 50]:    " + inclusive);
        System.out.println("snapshot copy:      " + snapshot);
    }
}

How It Works

  1. Two-arg excludes upper bound. subSet(20, 50) keeps 20 and 35, stopping just before 50.
  2. Four-arg controls both ends. Passing true, true pulls 50 into the slice as well.
  3. Copy for decoupling. Wrapping mid in new TreeSet<>(mid) creates an independent set.

Example 2 — Live View Updates and Out-of-Range Writes

Add an in-range element through a subSet view, see the original update, then check an out-of-range insert vs lookup.

Java
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetSubSetLive {
    public static void main(String[] args) {
        NavigableSet<Integer> ports = new TreeSet<>(Arrays.asList(80, 443, 8000, 8080, 9000));
        NavigableSet<Integer> appPorts = ports.subSet(8000, true, 8500, false);

        appPorts.add(8443);
        System.out.println("view after add:     " + appPorts);
        System.out.println("backing set synced: " + ports);
        System.out.println("view contains 80?   " + appPorts.contains(80));

        try {
            appPorts.add(9090);
        } catch (IllegalArgumentException e) {
            System.out.println("out-of-range add:   " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Write-through insertion. Adding 8443 via appPorts inserts 8443 directly into ports.
  2. Reads respect slice bounds. Port 80 is in ports, yet appPorts.contains(80) returns false without throwing.
  3. Out-of-range writes fail. Adding 9090 exceeds 8500, so the view rejects it with IllegalArgumentException.

Example 3 — Alphabetical Directory Slice and Reversed Bounds Error

Slice names starting from "A" up to "N", test an empty equal-bounds view, and catch reversed bounds.

Java
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetSubSetStrings {
    public static void main(String[] args) {
        NavigableSet<String> names = new TreeSet<>(Arrays.asList("Amy", "Ben", "Mia", "Noah", "Zoe"));

        System.out.println("A through M:  " + names.subSet("A", "N"));
        System.out.println("empty equal:  " + names.subSet("Ben", false, "Ben", false));

        try {
            names.subSet("Z", "A");
        } catch (IllegalArgumentException e) {
            System.out.println("reversed:     " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Open string upper bound. Because "Mia" < "N", using "N" as an exclusive cap cleanly captures every name starting with A through M.
  2. Equal bounds stay valid. Passing "Ben" twice with exclusive flags gives an empty view [] without error.
  3. Lower bound cannot exceed upper. Asking for subSet("Z", "A") throws IllegalArgumentException.

Frequently Asked Questions

fromElement is inclusive and toElement is exclusive by default. Pass booleans to the four-arg overload to control each end.
No. It returns a live backed view, so changes affect both sides. Wrap it in new TreeSet<>(sub) for an independent copy.
You tried to add an element outside the view bounds, or created a subSet where fromElement > toElement.
It returns false instead of throwing IllegalArgumentException, even if x exists in the backing TreeSet.
The two-arg overload returns SortedSet (since Java 1.2) with fixed [from, to) bounds; the four-arg overload returns NavigableSet (since Java 6) with explicit boolean flags.

Next: headSet()

Get a live view of elements smaller than (or up to) a bound.

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

10 people found this page helpful