VOOZH about

URL: https://www.geeksforgeeks.org/java/creating-subsets-and-headsets-from-treemap-with-java/

⇱ Creating Subsets and Headsets from TreeMap with Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Creating Subsets and Headsets from TreeMap with Java

Last Updated : 23 Jul, 2025

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.

How to Create Subsets and Headsets from a TreeMap Based on Specific Criteria in Java?

Approaches to create subsets and headsets from a TreeMap

  • SubMap(): TreeMap's subMap(K fromKey, K toKey) function yields a view of the area of the map whose keys fall between fromKey and toKey.
  • HeadMap(): The part of the map whose keys are strictly smaller than toKey is shown in the view returned by the TreeMap headMap(K toKey) function.

1. Creating a Subset using subMap()

Below is the implementation of Creating a Subset using subMap() :


Output
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}


Explanation of the Program:

  • In the above program, a TreeMap is created.
  • A subset is created from the original TreeMap using the subMap() method. This specifies the start (inclusive) and end (exclusive) keys.
  • The original TreeMap and the subset are printed to the console.

2. Creating a Headset using headMap

Below is the implementation of Creating a Headset using headMap:


Output
Original TreeMap: {1=A, 2=B, 3=C, 4=D, 5=E}
Headset (up to key 4, exclusive): {1=A, 2=B, 3=C}


Explanation of the Program:

  • In the above program, a TreeMap is created.
  • A headset is created from the original TreeMap using the headMap() method, specifying the end key (exclusive).
  • The original TreeMap and the headset are printed to the console.
Comment