Java TreeSet subSet() Method
Example
Get the numbers between 20 and 40:
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.subSet(20, 40));
System.out.println(numbers.subSet(20, false, 40, true));
}
}
Definition and Usage
The subSet() method returns the part of the set with the items between two values. By default, the first value is included and the last value is not. Use the version with four parameters to choose if each of the two values is included.
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 headSet() and tailSet() methods to get the start or the end of the set.
Syntax
One of the following:
public SortedSet<T> subSet(T fromItem, T toItem)
public NavigableSet<T> subSet(T fromItem, boolean fromInclusive, T toItem, boolean toInclusive)
T refers to the data type of items in the set.
Parameter Values
| Parameter | Description |
|---|---|
| fromItem | Required. The first value of the part to return. It does not have to be in the set. |
| fromInclusive | Optional. If false, the returned set does not have fromItem. The default is true. |
| toItem | Required. The last value of the part to return. It does not have to be in the set. |
| toInclusive | Optional. If true, the returned set also has toItem. The default is false. |
Technical Details
| Returns: | A set with the items between fromItem and toItem. |
|---|---|
| Throws: | IllegalArgumentException - if fromItem is greater than toItem. |
Related Pages
❮ TreeSet Methods