Java TreeSet - subList() Method
The java.util.TreeSet.subList() method returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromInclusive and toInclusive are both true. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
Syntax
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
Here, E is the type of element maintained by the container.
Parameters
fromElement |
Specify the low endpoint of the returned set. |
fromInclusive |
Specify true if the low endpoint is to be included in the returned view. |
toElement |
Specify the high endpoint of the returned set. |
toInclusive |
Specify true if the high endpoint is to be included in the returned view. |
Return Value
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
Exception
- Throws ClassCastException, if fromElement and toElement cannot be compared to one another using this set's comparator (or, if the set has no comparator, using natural ordering).
- Throws NullPointerException, if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements.
- Throws IllegalArgumentException, if fromElement is greater than toElement; or if this set itself has a restricted range, and fromElement or toElement lies outside the bounds of the range.
Example:
In the example below, the java.util.TreeSet.subList() method returns a view of the portion of the given treeset.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating treesets TreeSet<Integer> MySet = new TreeSet<Integer>(); TreeSet<Integer> MySubSet = new TreeSet<Integer>(); //populating the set MySet.add(10); MySet.add(20); MySet.add(-30); MySet.add(40); MySet.add(50); MySet.add(-60); MySet.add(70); //printing the set System.out.println("MySet contains: "+ MySet); //creating a portion view of the set MySubSet = (TreeSet<Integer>)MySet.subSet(10, false, 50, false); //printing the subset System.out.println("MySubSet contains: "+ MySubSet); } }
The output of the above code will be:
MySet contains: [-60, -30, 10, 20, 40, 50, 70] MySubSet contains: [20, 40]
❮ Java.util - TreeSet