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, if inclusive is true) 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 NavigableSet<E> tailSet(E toElement, boolean inclusive)
Here, E is the type of element maintained by the container.
Parameters
toElement |
Specify the low endpoint of the returned set. |
inclusive |
Specify true if the low endpoint is to be included in the returned view. |
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, if inclusive is true) 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(excluding) Set2 = (TreeSet<Integer>)Set1.tailSet(30, false); //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: [40, 50]
❮ Java.util - TreeSet