SubSet with Navigation: headSet, tailSet, and subSet
You'll learn how to create precise range views of a NavigableSet by controlling whether boundary elements are included or excluded.
Core Concept
NavigableSet provides powerful versions of headSet, tailSet, and subSet that let you specify exactly whether the boundary values should be included (inclusive) or excluded (exclusive) from your view. These methods accept boolean parameters to give you fine-grained control over the range edges.
The Methods
headSet(E toElement, boolean inclusive)
Returns all elements less than toElement. If inclusive is true, elements equal to toElement are also included.
tailSet(E fromElement, boolean inclusive)
Returns all elements greater than fromElement. If inclusive is true, elements equal to fromElement are also included.
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
Returns all elements in the range from fromElement to toElement, with separate boolean flags controlling inclusion at each boundary.
Why This Matters
Think of these methods like defining mathematical intervals. Sometimes you want [5, 10] (both endpoints included), sometimes (5, 10) (both excluded), or mixed like [5, 10) (left included, right excluded). The boolean parameters give you exactly this flexibility.
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(1); numbers.add(5); numbers.add(10); numbers.add(15); numbers.add(20);
NavigableSet<Integer> view1 = numbers.headSet(10, true); // {1, 5, 10}
NavigableSet<Integer> view2 = numbers.headSet(10, false); // {1, 5}
NavigableSet<Integer> view3 = numbers.subSet(5, true, 15, false); // {5, 10}
Key Takeaway: NavigableSet's overloaded range methods with boolean parameters let you precisely control whether boundary elements are included or excluded, giving you mathematical interval-like control over your set views.