Java TreeSet headSet() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

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.

Java
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]
CallWhat 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
// 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

ParameterDescription
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 ValueDescription
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:

MethodHow 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

Example 1 — Separate Failing Scores Below 60 With headSet()

Compare exclusive headSet(60) against inclusive headSet(60, true) on exam marks.

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

How It Works

  1. Exclusive by default. One-argument headSet(60) stops before 60, returning [38, 52].
  2. Boolean flag flips endpoint. Passing true includes 60, yielding [38, 52, 60].
  3. 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.

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

How It Works

  1. Slice everything before 1000. logIds.headSet(1000) views 910, 955, and 999 while keeping 1000 untouched.
  2. Delete through the view. Calling clear() drops only those three expired IDs directly from logIds.
  3. 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.

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

How It Works

  1. In-bound add propagates. Because "c-test" < "m", early.add("c-test") inserts it into both early and tasks.
  2. Boundary enforced on write. "m-review" is greater than "m", exceeding the exclusive bound of early.
  3. IllegalArgumentException thrown. The out-of-range insert fails without altering tasks.

Frequently Asked Questions

No, by default headSet(toElement) is exclusive (< toElement). Use headSet(toElement, true) to include it.
No. It returns a live backed view. Removing or adding elements inside the view updates the original TreeSet directly.
Call set.headSet(limit).clear(). That deletes every element strictly below limit in one step.
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).
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

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.

11 people found this page helpful