Skip to content

Get headSet, tailSet and subSet from Java TreeSet

This example shows how to get headset, tailset, and subset from the TreeSet object using the headSet, tailSet, and subSet methods of the TreeSet class in Java.

How to get a headset from TreeSet using the headSet method?

The headSet method of the TreeSet class returns a Set view of a part of the TreeSet containing elements less than the specified element.

The returned Set will contain all the TreeSet elements that are less than the specified element. The specified element will not be present in the resulting headset.

Output

As we can see from the output, the element 6 was not included in the headset. If you want to include the specified element in the headset, you can use the overloaded headSet method that also accepts a boolean parameter.

Output

How to get a tailset from TreeSet using the tailSet method?

The tailSet method of the TreeSet class returns a Set view of a part of the TreeSet containing elements greater than or equal to the specified element.

The returned Set will contain all the TreeSet elements that are greater than or equal to the specified element.

Output

If you do not want the specified element to be returned in the tailset, you can use the overloaded tailSet method that also accepts a boolean parameter.

Output

How to get a subset from TreeSet using the subSet method?

The subSet method of the TreeSet class returns a view of part of the TreeSet whose elements range from given start and end elements.

Here, the fromElement is inclusive while the toElement is exclusive.

Output

If you want to specify the inclusiveness of the from or to elements, you can use the overloaded subSet method.

This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.