Java Utility Library

Java HashMap - remove() Method



The java.util.HashMap.remove() method is used to remove the mapping for the specified key from this map if present.

Syntax

public V remove(Object key)

Here, V is the type of value maintained by the container.


Parameters

key Specify key whose mapping is to be removed from the map.

Return Value

Returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Exception

NA.

Example:

In the example below, the java.util.HashMap.remove() method is used to remove the mapping for the specified key from the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //printing MyMap
    System.out.println("Before remove, MyMap contains: " + MyMap);    

    //remove mapping for 102 key
    MyMap.remove(102); 

    //printing MyMap
    System.out.println("After remove, MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

Before remove, MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo}
After remove, MyMap contains: {101=John, 103=Kim, 104=Jo}

❮ Java.util - HashMap