1. Introduction
A TreeMap is a part of the Java Collections Framework and extends the AbstractMap class. It is a Red-Black tree-based NavigableMap implementation, which means it maintains its keys in natural order or based on a provided comparator. In this guide, we’ll explore the CRUD (Create, Read, Update, Delete) operations on a TreeMap.
2. Program Steps
1. Initialize a TreeMap.
2. Populate the TreeMap with key-value pairs (Create).
3. Retrieve a value by its key from the TreeMap (Read).
4. Modify the value of an existing key (Update).
5. Remove a key-value pair from the TreeMap (Delete).
6. Display the final state of the TreeMap.
3. Code Program
import java.util.TreeMap;
public class TreeMapCRUDExample {
public static void main(String[] args) {
// 1. Initialize a TreeMap
TreeMap<String, Integer> scores = new TreeMap<>();
// 2. Populate the TreeMap with key-value pairs (Create)
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 88);
System.out.println("Initial TreeMap: " + scores);
// 3. Retrieve a value by its key from the TreeMap (Read)
int aliceScore = scores.get("Alice");
System.out.println("Score of Alice: " + aliceScore);
// 4. Modify the value of an existing key (Update)
scores.put("Alice", 92);
System.out.println("Updated score of Alice: " + scores.get("Alice"));
// 5. Remove a key-value pair from the TreeMap (Delete)
scores.remove("Bob");
System.out.println("After deleting Bob's score: " + scores);
// 6. Display the final state of the TreeMap
System.out.println("Final TreeMap: " + scores);
}
}
Output:
Initial TreeMap: {Alice=90, Bob=85, Charlie=88} Score of Alice: 90 Updated score of Alice: 92 After deleting Bob's score: {Alice=92, Charlie=88} Final TreeMap: {Alice=92, Charlie=88}
4. Step By Step Explanation
1. A TreeMap is instantiated using its default constructor, ensuring that its entries are sorted according to their natural ordering.
2. The put method is employed to insert key-value pairs into the TreeMap.
3. By utilizing the get method, we can fetch the value linked with a particular key.
4. Updating the value of an existing key is done using the put method with a key that's already present.
5. The remove method lets us delete a given key-value pair from the TreeMap.
6. We print the state of the TreeMap several times during the program to monitor the various changes.
This tutorial provides a concise introduction to the basic CRUD operations using a TreeMap in Java, emphasizing its key sorting feature.