What is the NavigableSet.headSet() method in Java?

In this shot, we will learn how to use the NavigableSet.headSet() method in Java. The headSet() method is present in the NavigableSet interface inside the java.util package.

Variants of the headSet() method

The NavigableSet.headSet() is available in two variations:

  • First variation: This variation is used to obtain the parts of the set whose elements are less than or equal to the element if the pred (Boolean value) is true.

  • Second variation: This variation of the NavigableSet.headSet() function is used to obtain the parts of the set whose elements are less than the element.

When we add the elements in the NavigableSet, they get stored in the sorted form. If the NavigableSet is of String type, the elements get stored in alphabetical order irrespective of string length.

Parameters

The first variation of NavigableSet.headSet() accepts two parameters:

  • Element: The element that is the highest point for the returned range.

  • Pred: It is specified as true when the high endpoint is to be included in the returned view.

The second variation of the NavigableSet.headSet() accepts only one parameter, i.e., the element that is the highest point for the returned range.

Return value

The first variation of the NavigableSet.headSet() method returns the set in which the elements are less than or equal to the element if the pred is passed as true.

The second NavigableSet.headSet() method returns the set in which the elements are less than the element passed in the argument.

Code

Let’s have a look at the code.

import java.util.NavigableSet;
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
NavigableSet<Integer> s = new TreeSet<Integer>();
s.add(6);
s.add(8);
s.add(5);
s.add(3);
s.add(9);
s.add(10);
s.add(17);
System.out.println("Values less than or equal to 9: " + s.headSet(9, true));
System.out.println("Values less than 9 are: " + s.headSet(9));
}
}

Explanation

  • In lines 1 and 2, we imported the required packages and classes.

  • In line 4, we made the Main class.

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

  • In line 6, we created a TreeSet of Integer type. The NavigableSet is inherited from SortedSet which is actually inherited from TreeSet only. As SortedSet and NavigableSet are interfaces, we cannot instantiate an object of them.

  • From lines 8 to 14, we added the elements into the NavigableSet by using the add() method.

  • From line 16, we used the first variation of NavigableSet.headSet() method to obtain headSet and displayed the result with a message.

  • In line 17, we used the second variation of NavigableSet.headSet() method to obtain headSet and displayed the result with a message.

In this way, we can use the NavigableSet.headSet() method in Java.

Free Resources