Java TreeSet headSet() Method
Example
Get the numbers that are less than 30, first without and then with 30 itself:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<Integer>();
numbers.add(40);
numbers.add(10);
numbers.add(30);
numbers.add(20);
System.out.println(numbers.headSet(30));
System.out.println(numbers.headSet(30, true));
}
}
Definition and Usage
The headSet() method returns the part of the set with the items that are less than the specified value. By default, the value itself is not included. Set the second parameter to true to include it.
The returned set is a view of the original set (it shows the same items, it is not a copy). If you change one of them, the other one changes too.
Tip: Use the tailSet() method to get the items from a given value to the end of the set.
Syntax
One of the following:
public SortedSet<T> headSet(T toItem)
public NavigableSet<T> headSet(T toItem, boolean inclusive)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| toItem | Required. The returned set has the items that are less than this value. It does not have to be in the set. |
| inclusive | Optional. If true, the returned set also has toItem (if it is in the set). The default is false. |
Technical Details
| Returns: | A set with the items that are less than toItem (or equal to it, if inclusive is true). |
|---|
Related Pages
❮ TreeSet Methods