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() :
// Java program to create subsets from a TreeMap
import java.util.TreeMap;
public class SubSetExample {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "A");
treeMap.put(2, "B");
treeMap.put(3, "C");
treeMap.put(4, "D");
treeMap.put(5, "E");
// creating a subset from key 3 (inclusive) to key 5 (exclusive)
TreeMap<Integer, String> subMap = new TreeMap<>(treeMap.subMap(3, 5));
System.out.println("Original TreeMap: " + treeMap);
System.out.println("Subset (inclusive of key 3, exclusive of key 5): " + 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
TreeMapis created. - A subset is created from the original
TreeMapusing thesubMap()method. This specifies the start (inclusive) and end (exclusive) keys. - The original
TreeMapand the subset are printed to the console.
2. Creating a Headset using headMap
Below is the implementation of Creating a Headset using headMap:
// Java program to create headsets from a TreeMap
import java.util.TreeMap;
public class HeadSetExample {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "A");
treeMap.put(2, "B");
treeMap.put(3, "C");
treeMap.put(4, "D");
treeMap.put(5, "E");
// Creating a headset up to key 4 (exclusive)
TreeMap<Integer, String> headMap = new TreeMap<>(treeMap.headMap(4));
System.out.println("Original TreeMap: " + treeMap);
System.out.println("Headset (up to key 4, exclusive): " + 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
TreeMapis created. - A headset is created from the original
TreeMapusing theheadMap()method, specifying the end key (exclusive). - The original
TreeMapand the headset are printed to the console.