Get submap headmap and tailmap from Java TreeMap Example

This example shows how to get a submap, headmap, and tailmap from the TreeMap in Java. This example also shows how to use the subMap, headMap, and tailMap methods of the TreeMap class.

How to get submap, headmap, and tailmap from the TreeMap in Java?

The TreeMap class in Java provides methods to get each type of map as given below.

How to get a submap using the subMap method?

The subMap method of the TreeMap class returns a view of part of the TreeMap whose keys are in between the specified start and end keys.

Here, the startKey is inclusive (i.e. will be included in the submap) and the endKey is exclusive (i.e. will not be included in the submap).

Output

The subMap method throws IllegalArgumentException exception if the start key is greater than the end key parameter.

By default, the start key is inclusive while the end key is exclusive in the subMap method. If you want to change the inclusiveness, you can use the below given overloaded subMap method.

How to get a headmap using the headMap method?

The headMap method returns a view of part of the TreeMap object whose keys are less than the specified end key.

The end key is exclusive i.e. will not be included in the head map.

Output

Here, the end key is exclusive. If you want to control that, you can use the overloaded headMap method that has an inclusiveness parameter.

How to get a tailmap using the tailMap method?

The tailMap method returns a view of the part of the TreeMap whose keys are greater than or equal to the specified start key.

The specified start key is inclusive i.e. will be included in the tail map.

Output

By default, the specified start key is included in the tail map. If you do not want that, you can use the overloaded tailMap method and specify false as a second parameter.

Important Note:

The submaps returned by the subMap, headMap and tailMap methods are backed by the original TreeMap and support all operations that are supported by the TreeMap object. Any changes you make to the submaps will be reflected in the TreeMap, and vice versa.

Output

However, keep in mind that if you try to put an entry in the submap which is out of the range of the submap, the code will throw IllegalArgumentException exception.

Output

This example is a part of the TreeMap in Java Tutorial.

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

References:
Java 8 TreeMap

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 *