1. Introduction
In Java, the HashMap class is a part of the Java Collections Framework and is used to store key-value pairs. One of the common operations performed on a HashMap is removing a key-value pair using the remove() method. This method removes the mapping for a key from this map if it is present, and returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.
2. Program Steps
1. Create a HashMap object and populate it with some key-value pairs.
2. Print the original HashMap.
3. Use the remove() method to remove a key-value pair using a specific key.
4. Print the HashMap after removing the key-value pair.
3. Code Program
import java.util.HashMap;
public class HashMapRemove {
public static void main(String[] args) {
// Step 1: Create a HashMap object and populate it with some key-value pairs
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
// Step 2: Print the original HashMap
System.out.println("Original HashMap: " + map);
// Step 3: Use the remove() method to remove a key-value pair using a specific key
Integer removedValue = map.remove("Banana");
// Step 4: Print the HashMap after removing the key-value pair
System.out.println("HashMap after removing 'Banana': " + map);
System.out.println("Removed value: " + removedValue);
}
}
Output:
Original HashMap: {Banana=20, Apple=10, Cherry=30} HashMap after removing 'Banana': {Apple=10, Cherry=30} Removed value: 20
4. Step By Step Explanation
Step 1: A HashMap object named map is created, and it is populated with three key-value pairs: "Apple" with value 10, "Banana" with value 20, and "Cherry" with value 30.
Step 2: The original HashMap, which contains all the added key-value pairs, is printed.
Step 3: The remove() method is called with the key "Banana". This method removes the key-value pair associated with "Banana" from the HashMap and returns the value that was associated with the key, which is 20 in this case.
Step 4: The HashMap after removing the key-value pair and the removed value are printed. The resulting HashMap no longer contains the key "Banana" and its associated value 20.