What is the SortedSet.headSet() function in Java?

In this shot, we will learn how to use the SortedSet.headSet() method in Java.

Introduction

The SortedSet.headSet() method is present in the SortedSet interface inside the java.util package. The SortedSet.headSet() is used to return the elements up to a highest given limit, i.e., elements less 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 1212. The headset for this sorted set will be 1, 3, 5, 8, 9. Hence, the result of the SortedSet.headSet() method is 1, 3, 5, 8, 9.

Parameter

The SortedSet.headSet() method accepts the below parameter:

  • Limit_element: The limit up to which SortedSet is allowed to return values, excluding the limit itself.

Return

The SortedSet.headSet() method returns the elements of the SortedSet up to the limit excluding the Limit_element in the 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.println("The resultant elements of the headset are: "+set.headSet(10));
}
}

Explanation:

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

  • In line 4, we made a Main class.

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

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

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

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

  • In lines 19, we displayed the headset of the SortedSet with the message.

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

Free Resources