Java TreeSet - tailSet() Method
The java.util.TreeSet.tailSet() method returns a view of the portion of this set whose elements are greater than or equal to fromElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.
Syntax
public SortedSet<E> tailSet(E toElement)
Here, E is the type of element maintained by the container.
Parameters
toElement |
Specify the low endpoint (inclusive) of the returned set. |
Return Value
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
Exception
- Throws ClassCastException, if toElement is not compatible with this set's comparator (or, if the set has no comparator, if toElement does not implement Comparable).
- Throws NullPointerException, if toElement is null and this set uses natural ordering, or its comparator does not permit null elements.
- Throws IllegalArgumentException, if this set itself has a restricted range, and toElement lies outside the bounds of the range.
Example:
In the example below, the java.util.TreeSet.tailSet() method returns a view of the portion of the given set containing elements greater than or equal to the specified value.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treeset TreeSet<Integer> Set1 = new TreeSet<Integer>(); TreeSet<Integer> Set2 = new TreeSet<Integer>(); //populating Set1 Set1.add(10); Set1.add(20); Set1.add(30); Set1.add(40); Set1.add(50); //printing the Set1 System.out.println("Set1 contains: " + Set1); //creating the tailset //(limiting the value till 30) Set2 = (TreeSet<Integer>)Set1.tailSet(30); //printing the Set2 System.out.println("Set2 contains: " + Set2); } }
The output of the above code will be:
Set1 contains: [10, 20, 30, 40, 50] Set2 contains: [30, 40, 50]
❮ Java.util - TreeSet