What is the TreeSet.tailSet() function in Java?
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)
Parameters
Limit_element: The limit from whichTreeSetis allowed to return values, including the limit itself.
Return value
- Elements:
TreeSet.tailSet()returns the elements of theTreeSetfrom the limit, including theLimit_elementto the last element in a sorted manner.
Example
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
Code
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() + " ");}}
Explanation
- In line 8 we declare a
TreeSetofIntegertype. - In lines 9 to 15 we add the elements into the
TreeSetwith theTreeSet.add()method. - In line 16 we display the original
TreeSetwith a message. - In line 18 we declare another
TreeSetto store thetailset. - In line 19 we call the
TreeSet.tailSet()method with a limit from which the elements need to be returned, and store thetailsetin theTreeSetfrom line 18. - In line 21 we make an object of
Iteratorclass. - In line 22 we iterate and assign the
TreeSetthat contains thetailsetto theIteratorobject. - In line 24 we display the message regarding the
tailset. - In lines 25 and 26 we use a
whileloop to traverse over thetailsetusing theIteratorobjectTreeSetand display the elements of thetailset.
In this way, we can use the TreeSet.tailSet() method to obtain the tailset from a limit to the last element of the TreeSet.