Related Tags

java
communitycreator

# What is the SortedSet.tailSet() function in Java?

Harsh Jain

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The SortedSet.tailSet() method is present in the SortedSet interface inside the java.util package. SortedSet.tailSet() is used to return the elements after a given limit, including the limit, i.e., elements greater or equal than the given limit.

Let’s understand with the help of an example. Suppose that a SortedSet contains [1, 3, 5, 8, 9, 12, 15, 23, 25] and the limit is $12$. The tailset for this sorted set will be 12, 15, 23, 25. Therefore, the result of the SortedSet.tailSet() method is 12, 15, 23, 25.

### Syntax

SortedSet.tailSet(limit_element)


### Parameters

• limit_element: The limit from which SortedSet is allowed to return a value, including the limit itself.

### Return value

The SortedSet.tailSet() method returns the elements of the SortedSet from the limit, including the limit_element, in a sorted manner.

### Code

Let’s have a look at the code now.

import java.io.*;import java.util.SortedSet;import java.util.TreeSet;class Main {  public static void main(String args[])  {    SortedSet<Integer> set = new TreeSet<Integer>();    set.add(1);    set.add(8);    set.add(5);    set.add(3);    set.add(0);    set.add(22);    set.add(10);    System.out.println("SortedSet: " + set);    System.out.print("The resultant elements of the tailset are: "+set.tailSet(10));  }}
Use the SortedSet.tailSet() function in Java

### Explanation

• From lines 1 to 3, we import the required packages and classes.

• In line 4, we make a Main class.

• In line 6, we make a main() function.

• In line 8, we create a TreeSet of Integer type. The SortedSet is actually only inherited from TreeSet. As SortedSet is an interface, we cannot instantiate an object of it.

• From lines 10 to 16, we use the SortedSet.add() method to add the elements into the SortedSet.

• In line 17, we display the original SortedSet with a message.

• In line 19, we display the tailset of the SortedSet with the message.

So, this is how to use the TreeSet.tailSet() method in Java.

RELATED TAGS

java
communitycreator

CONTRIBUTOR

Harsh Jain