![]() |
VOOZH | about |
A Java TreeMap is a sorted collection that is a component of the Java Collections Framework. Subsets are parts of the map, and headsets are made up of items that are less than or equal to a specified key.
In this article, we will learn how to create subsets and headsets from a TreeMap based on specific criteria in Java.
Approaches to create subsets and headsets from a TreeMap
Below is the implementation of Creating a Subset using subMap() :
Original TreeMap: {1=A, 2=B, 3=C, 4=D, 5=E}
Subset (inclusive of key 3, exclusive of key 5): {3=C, 4=D}
TreeMap is created.TreeMap using the subMap() method. This specifies the start (inclusive) and end (exclusive) keys.TreeMap and the subset are printed to the console.Below is the implementation of Creating a Headset using headMap:
Original TreeMap: {1=A, 2=B, 3=C, 4=D, 5=E}
Headset (up to key 4, exclusive): {1=A, 2=B, 3=C}
TreeMap is created.TreeMap using the headMap() method, specifying the end key (exclusive).TreeMap and the headset are printed to the console.