The TreeSet.tailSet() method is present in the TreeSet class inside the java.util package. The TreeSet.tailSet() method is used to return the elements from a given limit to the last element of the TreeSet, including the limit element.
The method prototype is as follows:
TreeSet tail_set.tailSet(Object element)
Limit_element: The limit from which TreeSet is allowed to return values, including the limit itself.TreeSet.tailSet() returns the elements of the TreeSet from the limit, including the Limit_element to the last element in a sorted manner.Let’s understand with the help of an example.
We have a TreeSet = [1,3,5,8,9,12,15,23,25]
Limit = 9
The tailset should be 9, 12, 15, 23, 25
So, the result of the TreeSet.tailSet() method is 9, 12, 15, 23, 25
Let’s look at the code snippet.
import java.io.*;import java.util.*;class Main{public static void main(String args[]){TreeSet<Integer> tree_set = new TreeSet<Integer>();tree_set.add(1);tree_set.add(8);tree_set.add(5);tree_set.add(3);tree_set.add(0);tree_set.add(22);tree_set.add(10);System.out.println("TreeSet: " + tree_set);TreeSet<Integer> tailset = new TreeSet<Integer>();tailset = (TreeSet<Integer>)tree_set.tailSet(5);Iterator i;i=tailset.iterator();System.out.print("The resultant elements of the tailset are: ");while (i.hasNext())System.out.print(i.next() + " ");}}
TreeSet of Integer type.TreeSet with the TreeSet.add() method.TreeSet with a message.TreeSet to store the tailset.TreeSet.tailSet() method with a limit from which the elements need to be returned, and store the tailset in the TreeSet from line 18.Iterator class.TreeSet that contains the tailset to the Iterator object.tailset.while loop to traverse over the tailset using the Iterator object TreeSet and display the elements of the tailset.In this way, we can use the TreeSet.tailSet() method to obtain the tailset from a limit to the last element of the TreeSet.