Java HashMap remove(Object o) Method Example

The remove(Object o) method will remove the mapping for the specified key from this map if present.

Signature

public V remove(Object key)

This method removes the mapping for the specified key from this map if present and returns the previous value associated with key or null if there was no mapping for key.

Example

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

import java.util.HashMap;
import java.util.Map;

public class RemoveMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String> hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap1
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        System.out.println("**Elements of hashMap1 before remove()**");
        
        //Print the elements of hashMap1
        for (Map.Entry<Integer,String> entry : hashMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
        
        //lets remove the value associated to key "3"
        System.out.println("Element removed : \""+hashMap1.remove(3)+"\"");
        
        System.out.println("**Elements of hashMap1 after remove()**");
        //Print the elements of hashMap1
        for (Map.Entry<Integer,String> entry : hashMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
    }
}

Output

**Elements of hashMap1 before remove()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
Element removed : "Element3"
**Elements of hashMap1 after remove()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 4 Value : Element4
Key : 5 Value : Element5

Leave a Reply

Your email address will not be published. Required fields are marked *