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 which TreeSet is allowed to return values, including the limit itself.

Return value

  • Elements: TreeSet.tailSet() returns the elements of the TreeSet from the limit, including the Limit_element to 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 TreeSet of Integer type.
  • In lines 9 to 15 we add the elements into the TreeSet with the TreeSet.add() method.
  • In line 16 we display the original TreeSet with a message.
  • In line 18 we declare another TreeSet to store the tailset.
  • In line 19 we call the TreeSet.tailSet() method with a limit from which the elements need to be returned, and store the tailset in the TreeSet from line 18.
  • In line 21 we make an object of Iterator class.
  • In line 22 we iterate and assign the TreeSet that contains the tailset to the Iterator object.
  • In line 24 we display the message regarding the tailset.
  • In lines 25 and 26 we use a 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.

Free Resources