Remove Key-Value Mapping from HashMap Example in Java

In the last tutorial we have seen how to check if a HashMap is empty or not. In this tutorial we will see how to remove a specific mapping from HashMap using the key value of Key-value pair. We will be using remove(Object key) method to remove the mapping. I already shared how HashMap remove() method works internally in java.

Syntax :

public Value remove(Object key) : According to Oracle docs, it removes the mapping for the specified key from the map if present.

Program for Remove Mapping from HashMap 

import java.util.*;

 public class HashMapRemoveExample {
    public static void main(String args[]) {
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    // Adding Key and Value pairs to HashMap
    // Showing HashMap Elements
    System.out.println("HashMap Elements: " + hashmap);

    // Removing Key-Value pairs for key 22
    Object removedElement1 = hashmap.remove(22);
    System.out.println("Element removed is: " +removedElement1);
    // Removing Key-Value pairs for key 44
    Object removedElement2 = hashmap.remove(44);
    System.out.println("Element removed is: " +removedElement2);

    // Displaying HashMap Elements after remove
    System.out.println("After Remove:");
    System.out.println("HashMap Elements: " + hashmap);

HashMap Elements:{33=Value3, 66=Value6, 22=Value2, 55=Value5, 11=Value1, 44=Value4}
Element removed is: Value2
Element removed is: Value4
After Remove:
HashMap Elements: {33=Value3, 66=Value6, 55=Value5, 11=Value1}

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry