Java Utility Library

Java TreeSet - subList() Method



The java.util.TreeSet.subList() method returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. (If fromElement and toElement are equal, the returned set is empty.) 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 SortedSet<E> subSet(E fromElement, 
                           E toElement)

Here, E is the type of element maintained by the container.


Parameters

fromElement Specify the low endpoint (inclusive) of the returned set.
toElement Specify the high endpoint (exclusive) of the returned set.

Return Value

Returns a view of the specified range within this List.

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, 50);

    //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: [10, 20, 40]

❮ Java.util - TreeSet