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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping