1. Introduction
HashMap is a part of the Java Collections Framework and is found in the java.util package. It is a data structure that employs a hashtable to implement the Map interface, allowing for the efficient retrieval of values based on their associated keys. The HashMap class permits null values and the null key. In this article, we will explore the CRUD (Create, Read, Update, Delete) operations on a HashMap.
2. Program Steps
1. Initialize a HashMap.
2. Populate the HashMap with key-value pairs (Create).
3. Retrieve a value by its key from the HashMap (Read).
4. Modify the value of an existing key (Update).
5. Remove a key-value pair from the HashMap (Delete).
6. Display the final state of the HashMap.
3. Code Program
import java.util.HashMap;
public class HashMapCRUDExample {
public static void main(String[] args) {
// 1. Initialize a HashMap
HashMap<String, Integer> scores = new HashMap<>();
// 2. Populate the HashMap with key-value pairs (Create)
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 88);
System.out.println("Initial HashMap: " + scores);
// 3. Retrieve a value by its key from the HashMap (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 HashMap (Delete)
scores.remove("Bob");
System.out.println("After deleting Bob's score: " + scores);
// 6. Display the final state of the HashMap
System.out.println("Final HashMap: " + scores);
}
}
Output:
Initial HashMap: {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 HashMap: {Alice=92, Charlie=88}
4. Step By Step Explanation
1. We commence by initializing an empty HashMap with String keys and Integer values.
2. The put method is employed to add key-value pairs into the HashMap.
3. Utilizing the get method, we can fetch the value associated with a specific key.
4. By employing the put method with an existing key, the associated value is updated.
5. The remove method is utilized to expunge a specific key-value pair from the HashMap.
6. At several intervals throughout the program, we exhibit the status of the HashMap to discern the changes.
Through this tutorial, we gain a better understanding of the CRUD operations in the context of a HashMap in Java.