In this section, we will learn what the TreeSet subSet() method is and how to use it in Java.
What is Java TreeSet subSet() Method?
The Java TreeSet subSet() method is used to get a view of a sub-set (portion of elements) of a TreeSet object.
Note: we say a view and not a copy! This means because both the view object (the return value of this method) and the target TreeSet object are backed by the same array of elements, if one of them changes something in that array, the other will notice.
Java subSet() Method Syntax:
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) public SortedSet<E> subSet(E fromElement, E toElement)
subSet() Method Parameters:
The method has two variants:
For the first variant, it takes four arguments:
- The first argument is the element in the set from which we want the view to start.
- The second argument if a boolean value that shows if the first argument should be inclusive or not. (The value true means first argument is inclusive)
- The third argument is the element where we want the view to end with.
- The last argument is a boolean value that shows if the third argument should be inclusive or not. The value true means this argument is in fact inclusive. The value false means otherwise.
For the second variant, it takes only two arguments:
- The first argument is an element from which we want the view to start. This value is inclusive.
- The second argument is the element where we want the view to end. This value is exclusive.
Note: The arguments of this method is the actual values in the target TreeSet object and not their indexes.
subSet() Method Return Value:
For the first variant of this method: The return value of this method is an object of type NavigableSet that is a view of the target TreeSet object.
But for the second variant of the method, the datatype is SortedSet.
Note: if the first and third arguments of this method are the same (equal number) the return value of this method will be empty unless both the second and fourth arguments are set to true as well.
subSet() Method Exceptions:
The method might throw three types of exceptions:
- ClassCastException: we get this exception if the first and third arguments of this method cannot be compared to each other because of datatype differences.
- NullPointerException: we get this exception if we put null values as the first or third argument of this method.
- IllegalArgumentException: we get this exception if the first argument of this method is bigger than the third argument.
Example: using TreeSet subSet() method
import java.util.TreeSet; import java.util.SortedSet; class Main{ public static void main(String[] args) { TreeSet<Integer> ts = new TreeSet<>(); ts.add(1); ts.add(2); ts.add(3); ts.add(0); ts.add(10); ts.add(30); ts.add(100); ts.add(200); ts.add(300); ts.add(400); ts.add(500); SortedSet<Integer> view = ts.subSet(10, 500); for (int i : view){ System.out.println(i); } } }
Output:
10 30 100 200 300 400