HashMap remove() Method Example

1. Introduction

The HashMap class in Java, part of the Collections Framework, is designed to store items in key-value pairs, enabling efficient retrieval, insertion, and deletion of elements based on keys. The remove(Object key) method is a significant functionality provided by the HashMap. It is used to remove the mapping for a key from this map if it is present. The method 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 and populate it with key-value pairs.

2. Demonstrate the removal of an element from the HashMap using the remove method.

3. Check the contents of the HashMap after the removal operation.

3. Code Program

import java.util.HashMap;

public class HashMapRemoveMethodExample {
    public static void main(String[] args) {
        // Step 1: Creating and populating a HashMap
        HashMap<Integer, String> employees = new HashMap<>();
        employees.put(101, "Amit");
        employees.put(102, "Vijay");
        employees.put(103, "Rahul");

        System.out.println("Original HashMap: " + employees);

        // Step 2: Removing a key-value pair from the HashMap
        String removedValue = employees.remove(102);
        System.out.println("Removed value: " + removedValue);

        // Step 3: Checking the contents of the HashMap after removal
        System.out.println("HashMap after removal: " + employees);
    }
}

Output:

Original HashMap: {101=Amit, 102=Vijay, 103=Rahul}
Removed value: Vijay
HashMap after removal: {101=Amit, 103=Rahul}

Explanation:

1. The HashMap named employees is created, mapping Integer keys (employee IDs) to String values (employee names). This demonstrates the process of setting up a HashMap with initial data.

2. The remove method is used to delete the entry with key 102 from the map. The method returns the value associated with the removed key, "Vijay", which is printed to the console. This illustrates how to use remove to delete a specific entry based on its key.

3. The final output shows the state of the HashMap after the removal operation. With the entry for key 102 removed, only the entries for keys 101 and 103 remain, demonstrating the effect of the remove method on the map's contents.

Comments