1. Introduction
The TreeMap in Java is a Red-Black tree based implementation of the Map interface. This class is part of Java’s collection framework and provides an efficient means of storing key-value pairs in sorted order. In this tutorial, we’ll look at how to access the entries of a TreeMap.
2. Program Steps
1. Create a TreeMap and populate it with some key-value pairs.
2. Access and display the first and last entries.
3. Retrieve a subset of the TreeMap using headMap, tailMap, and subMap methods.
4. Iterate over the TreeMap to display all entries.
3. Code Program
import java.util.TreeMap;
public class TreeMapAccess {
public static void main(String[] args) {
// Step 1: Create a TreeMap and populate it with some key-value pairs
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "One");
treeMap.put(3, "Three");
treeMap.put(2, "Two");
treeMap.put(4, "Four");
// Step 2: Access and display the first and last entries
System.out.println("First key: " + treeMap.firstKey() + " => First value: " + treeMap.get(treeMap.firstKey()));
System.out.println("Last key: " + treeMap.lastKey() + " => Last value: " + treeMap.get(treeMap.lastKey()));
// Step 3: Retrieve a subset of the TreeMap
System.out.println("HeadMap (keys less than 3): " + treeMap.headMap(3));
System.out.println("TailMap (keys greater than or equal to 3): " + treeMap.tailMap(3));
System.out.println("SubMap (keys in range 2 to 4): " + treeMap.subMap(2, 4));
// Step 4: Iterate over the TreeMap to display all entries
System.out.println("\nAll entries in the TreeMap:");
treeMap.forEach((key, value) -> System.out.println(key + " => " + value));
}
}
Output:
First key: 1 => First value: One Last key: 4 => Last value: Four HeadMap (keys less than 3): {1=One, 2=Two} TailMap (keys greater than or equal to 3): {3=Three, 4=Four} SubMap (keys in range 2 to 4): {2=Two, 3=Three} All entries in the TreeMap: 1 => One 2 => Two 3 => Three 4 => Four
4. Step By Step Explanation
Step 1: We initialize a TreeMap and populate it with some sample data. The TreeMap will keep its keys in natural ascending order.
Step 2: We access the first and last entries using firstKey and lastKey methods. These methods retrieve the smallest and largest keys respectively. We then use the get method to retrieve the associated values.
Step 3: The TreeMap class provides methods to access submaps:
– headMap(toKey): This method returns a view of the portion of the map whose keys are less than toKey.
– tailMap(fromKey): Returns a view of the portion of the map whose keys are greater than or equal to fromKey.
– subMap(fromKey, toKey): Returns a view of the portion of the map whose keys range from fromKey to toKey.
Step 4: We use the forEach method to iterate over the entries of the TreeMap and print them.