java.util.WeakHashMap.remove() Method



The remove(Object key) method is used to remove the mapping for this key from this map if present.


Following is the declaration for java.util.WeakHashMap.remove() method.

public Object remove(Object key)


  • key -- This is the key whose mapping is to be removed from the map.

Return Value

The method call returns the previous value associated with that key, or null if there was no mapping for key.


  • NA


The following example shows the usage of java.util.WeakHashMap.remove() method.

package com.tutorialspoint;

import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapDemo {
   public static void main(String[] args) { 
   Map<String, String> weakHashMap = new WeakHashMap<String, String>();
   // put keys and values in the Map
   System.out.println("Putting values into the Map");
   weakHashMap.put("1", "first");
   weakHashMap.put("2", "two");
   weakHashMap.put("3", "three");
   // checking Map
   System.out.println("Map: "+weakHashMap);
   // remove value at key 2      
   System.out.println("Returned value: "+weakHashMap.remove("2"));
   System.out.println("New Map: "+weakHashMap);

Let us compile and run the above program, this will produce the following result.

Putting values into the Map
Map: {1=first, 2=two, 3=three}
Returned value: two
New Map: {1=first, 3=three}