![]() |
VOOZH | about |
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
The headSet() method of TreeSet class been present inside java.util package is used as a limit setter for a tree set, to return the elements up to a limit defined in the parameter of the method in a sorted manner excluding the element.
Syntax:
head_set = (TreeSet)tree_set.headSet(Object element)
Parameters: The parameter element is of the type of the tree set and is the headpoint that is the limit up to which the tree is allowed to return values excluding the element itself.
Return Values: The method returns the portion of the values in a sorted manner that is strictly less than the element mentioned in the parameter.
now we will be discussing different scenarios while implementing the headSet() method in TreeSet class:
Example 1:
The resultant values till head set: 1 2 3 4 5 10 20
Example 2-A:
The resultant values till head set: 2 9 10 15 16 20
Example 2-B:
The resultant values till head set: 4 Geek Geeks