TreeSet headSet() Method in Java With Examples
The headSet()
method in Java is a part of the TreeSet
class which returns a view of the portion of the set whose elements are strictly less than the specified element. It returns a SortedSet
containing all the elements that are less than the specified element.
The syntax of the headSet()
method is as follows:
public SortedSet<E> headSet(E toElement)
Here, toElement
is the element that is used as the upper bound of the returned set.
The headSet()
method returns a view of the portion of the set whose elements are strictly less than the specified element. The returned set is backed by the original set, so changes made to the returned set are reflected in the original set, and vice versa.
Examples:
Let's consider a TreeSet
of integers and see how the headSet()
method works:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<Integer>();
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
set.add(60);
set.add(70);
set.add(80);
set.add(90);
set.add(100);
// Using headSet() method
SortedSet<Integer> headSet = set.headSet(50);
// Displaying the headSet
System.out.println("Head Set: " + headSet);
}
}
Output:
Head Set: [10, 20, 30, 40]
In the above example, we have created a TreeSet
of integers and added some elements to it. Then, we have used the headSet()
method to get a view of the portion of the set whose elements are strictly less than 50. The returned set contains all the elements that are less than 50, which are 10, 20, 30, and 40.
Another example:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<String>();
set.add("apple");
set.add("banana");
set.add("cherry");
set.add("date");
set.add("elderberry");
set.add("fig");
// Using headSet() method
SortedSet<String> headSet = set.headSet("date");
// Displaying the headSet
System.out.println("Head Set: " + headSet);
}
}
Output:
Head Set: [apple, banana, cherry]
In the above example, we have created a TreeSet
of strings and added some elements to it. Then, we have used the headSet()
method to get a view of the portion of the set whose elements are strictly less than "date". The returned set contains all the elements that are less than "date", which are "apple", "banana", and "cherry".