Java Utility Library

Java WeakHashMap - remove() Method



The java.util.WeakHashMap.remove() method is used to remove the mapping for a key from this weak hash map if it is 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.

Exception

NA.

Example:

In the example below, the java.util.WeakHashMap.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 weakhashmap
    WeakHashMap<Integer, String> MyMap = new WeakHashMap<Integer, String>();

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

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

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

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

The output of the above code will be:

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

❮ Java.util - WeakHashMap