Home Java TreeSet Methods headSet() Java TreeSet headSet() Method Definition In Java, headSet(toElement) returns a live view of every element in the TreeSet that is strictly less than toElement.
Adding the second argument headSet(toElement, inclusive) returns a NavigableSet and lets you pass true to include elements equal to toElement as well.
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 one-argument form dates back to Java 1.2 (SortedSet); the two-argument overload with an inclusive flag was added in Java 6 (NavigableSet).
Syntax Provide the upper cutoff; pass true as the second argument when the cutoff itself belongs in the view.
NavigableSet<Integer> grades = new TreeSet<>(Arrays.asList(45, 55, 60, 75));
SortedSet<Integer> below60 = grades.headSet(60); // [45, 55]
NavigableSet<Integer> upTo60 = grades.headSet(60, true); // [45, 55, 60] Call What it does set.headSet(to)All elements strictly less than to (returns SortedSet). set.headSet(to, true)All elements less than or equal to to (returns NavigableSet). set.headSet(cutoff).clear()Purges every element below cutoff from the original set. set.headSet(to).last()Finds the largest element strictly below to.
Because headSet() shares data with the original tree, creating a view takes O(1) time without copying elements.
Library declarations // java.util.TreeSet<E>
public SortedSet<E> headSet(E toElement)
public NavigableSet<E> headSet(E toElement, boolean inclusive)
// Declared in SortedSet<E> and NavigableSet<E> Parameters Parameter Description toElement (E)Upper bound for elements in the view. inclusive (boolean)Two-argument overload: true to include toElement, false to exclude it.
Return Value Return Value Description SortedSet<E> / NavigableSet<E>A live backed view containing the leading portion of the set.
Compare with Similar Methods Compare headSet() with the other range methods:
Method How it differs tailSet(from)Opposite side: elements from a lower bound to the end (inclusive by default). subSet(a, b)Bounded on both sides instead of only at the top. lower(to)Returns just the single largest element below to. floor(to)Returns just the single largest element at or below to.
Java Examples 1. Exclusive vs inclusive bound 2. Bulk purge old entries 3. Write-through and bounds error Example 1 — Separate Failing Scores Below 60 With headSet() Compare exclusive headSet(60) against inclusive headSet(60, true) on exam marks.
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
public class TreeSetHeadSetGrades {
public static void main(String[] args) {
NavigableSet<Integer> marks = new TreeSet<>(Arrays.asList(38, 52, 60, 74, 91));
SortedSet<Integer> strictlyBelow = marks.headSet(60);
NavigableSet<Integer> upToSixty = marks.headSet(60, true);
System.out.println("strictly < 60: " + strictlyBelow);
System.out.println("<= 60: " + upToSixty);
}
} strictly < 60: [38, 52]
<= 60: [38, 52, 60] How It Works Exclusive by default. One-argument headSet(60) stops before 60, returning [38, 52].Boolean flag flips endpoint. Passing true includes 60, yielding [38, 52, 60].Return types differ. The single-argument version returns SortedSet; the two-argument version returns NavigableSet.Example 2 — Purge Old Sequence IDs in One Line With headSet().clear() Delete all log sequence IDs older than 1000 from the main TreeSet using a temporary headSet view.
import java.util.Arrays;
import java.util.TreeSet;
public class TreeSetHeadSetPurge {
public static void main(String[] args) {
TreeSet<Integer> logIds = new TreeSet<>(Arrays.asList(910, 955, 999, 1000, 1042, 1105));
System.out.println("before purge: " + logIds);
logIds.headSet(1000).clear();
System.out.println("after purge: " + logIds);
System.out.println("oldest kept: " + logIds.first());
}
} before purge: [910, 955, 999, 1000, 1042, 1105]
after purge: [1000, 1042, 1105]
oldest kept: 1000 How It Works Slice everything before 1000. logIds.headSet(1000) views 910, 955, and 999 while keeping 1000 untouched.Delete through the view. Calling clear() drops only those three expired IDs directly from logIds.Clean boundary kept. 1000 becomes the new first() element.Example 3 — Add Through headSet() and Catch Out-of-Range Inserts Insert a valid element into a headSet view, see it appear in the backing set, and catch an invalid boundary insert.
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.TreeSet;
public class TreeSetHeadSetBounds {
public static void main(String[] args) {
NavigableSet<String> tasks = new TreeSet<>(Arrays.asList("a-init", "b-build", "m-deploy", "z-audit"));
NavigableSet<String> early = tasks.headSet("m", false);
early.add("c-test");
System.out.println("early view: " + early);
System.out.println("full tasks: " + tasks);
try {
early.add("m-review");
} catch (IllegalArgumentException e) {
System.out.println("adding >= m: " + e.getClass().getSimpleName());
}
}
} early view: [a-init, b-build, c-test]
full tasks: [a-init, b-build, c-test, m-deploy, z-audit]
adding >= m: IllegalArgumentException How It Works In-bound add propagates. Because "c-test" < "m", early.add("c-test") inserts it into both early and tasks.Boundary enforced on write. "m-review" is greater than "m", exceeding the exclusive bound of early.IllegalArgumentException thrown. The out-of-range insert fails without altering tasks.Frequently Asked Questions Does TreeSet headSet(toElement) include toElement? No, by default headSet(toElement) is exclusive (< toElement). Use headSet(toElement, true) to include it.
Does headSet() copy the elements into a new set? No. It returns a live backed view. Removing or adding elements inside the view updates the original TreeSet directly.
How do I delete all elements smaller than a value in a TreeSet? Call set.headSet(limit).clear(). That deletes every element strictly below limit in one step.
Why did headSet().add() throw IllegalArgumentException? The element you tried to add is outside the headSet upper limit (greater than or equal to an exclusive bound, or greater than an inclusive bound).
What is the opposite of headSet()? tailSet(), which views elements from a lower bound up to the end of the TreeSet.
Next: tailSet() Get a live view of elements greater than or equal to (or after) a bound.
tailSet() tutorial → 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.
11 people found this page helpful
Helpful Share Copy link Suggestion