What is the TreeSet.headSet() function in Java?
The TreeSet.headSet() method is present in the TreeSet class in the java.util package.
It is used to return the elements up to a given limit.
The following is the method prototype:
TreeSet head_set.headSet(Object element)
Parameters
The TreeSet.headSet() method takes the following parameter:
Limit_element: The limit up to whichTreeSetis allowed to return a value excluding the limit itself.
Return value
- Elements: It returns the elements of the
TreeSetup to the limit, excluding theLimit_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]
It has a limit: 15.
The headset should be 1 3 5 8 9 12.
So, the result of the TreeSet.headSet() method is 1 3 5 8 9 12.
Code
Let’s have a 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> headset = new TreeSet<Integer>();headset = (TreeSet<Integer>)tree_set.headSet(10);Iterator i;i=headset.iterator();System.out.print("The resultant elements of the headset are: ");while (i.hasNext())System.out.print(i.next() + " ");}}
Explanation
-
In line 8, we declared a
TreeSetofIntegertype. -
In lines 9 to 15, we added the elements into the
TreeSetby using theTreeSet.add()method. -
In line 16, we displayed the original
TreeSetwith a message. -
In line 18, we declared another
TreeSetto store the headset. -
In line 19, we called the
TreeSet.headSet()method with a limit and stored the headset in anotherTreeSetdeclared in line 18. -
In line 21, we made an object of the
Iteratorclass. -
In line 22, we iterated and assigned the
TreeSetcontaining the headset to the Iterator object. -
In line 24, we displayed the message regarding the headset.
-
In lines 25 and 26, we used a
whileloop to traverse over the headset using theIteratorobject and display the elements of the headset.
In this way, we can use the TreeSet.headSet() method to obtain the headset within a limit of the TreeSet.