Home Java TreeSet Methods subSet() Java TreeSet subSet() Method 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.
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] Call What 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.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 Parameter Description 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 Value Description SortedSet<E> / NavigableSet<E>A live view backed by the original TreeSet.
Compare with Similar Methods All range and reversed views on TreeSet:
Java Examples 1. Price bracket slice 2. Live write-through and bounds 3. String range and reversed bounds 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.
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);
}
} half-open [20, 50): [20, 35]
closed [20, 50]: [20, 35, 50]
snapshot copy: [20, 35] How It Works Two-arg excludes upper bound. subSet(20, 50) keeps 20 and 35, stopping just before 50.Four-arg controls both ends. Passing true, true pulls 50 into the slice as well.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.
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());
}
}
} view after add: [8000, 8080, 8443]
backing set synced: [80, 443, 8000, 8080, 8443, 9000]
view contains 80? false
out-of-range add: IllegalArgumentException How It Works Write-through insertion. Adding 8443 via appPorts inserts 8443 directly into ports.Reads respect slice bounds. Port 80 is in ports, yet appPorts.contains(80) returns false without throwing.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.
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());
}
}
} A through M: [Amy, Ben, Mia]
empty equal: []
reversed: IllegalArgumentException How It Works Open string upper bound. Because "Mia" < "N", using "N" as an exclusive cap cleanly captures every name starting with A through M.Equal bounds stay valid. Passing "Ben" twice with exclusive flags gives an empty view [] without error.Lower bound cannot exceed upper. Asking for subSet("Z", "A") throws IllegalArgumentException.Frequently Asked Questions Are the bounds in TreeSet subSet(from, to) inclusive? fromElement is inclusive and toElement is exclusive by default. Pass booleans to the four-arg overload to control each end.
Does subSet() create a copy of the TreeSet? No. It returns a live backed view, so changes affect both sides. Wrap it in new TreeSet<>(sub) for an independent copy.
Why does subSet().add() throw IllegalArgumentException? You tried to add an element outside the view bounds, or created a subSet where fromElement > toElement.
What does subSet().contains(x) do when x is out of range? It returns false instead of throwing IllegalArgumentException, even if x exists in the backing TreeSet.
What is the difference between the two-arg and four-arg subSet()? 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.
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.
10 people found this page helpful
Helpful Share Copy link Suggestion