What is remove in Java HashMap?

The remove function is used to remove value mapped to a key specified in the function.

If the key does not exist on the map, no changes take place.

Parameters

java.util.HashMap.remove(K key)

In the above snippet of code, key is the key stored in the HashMap. The value of an entity in the HashMap is stored corresponding to this key.

The type K of this key is specified when the HashMap is being declared.

Return value

If the key is not present in the HashMap, the remove function returns NULL.

If the key is present in the HashMap, that item is removed, and the remove function returns its value, as shown here:

Example-1:

import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
// making a hashmap with keys as integers and strings as corresponding values
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
hash_map.put(10, "Ten");
hash_map.put(20, "Twenty");
hash_map.put(30, "Thirty");
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
// using the remove function with an existing key
String returned_value = (String)hash_map.remove(20);
// displaying the value returned by using existing key with remove function
System.out.println("Value Returned : " + returned_value);
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
}
}

In the above example, we first make a HashMap of three values. Then, a valid key is passed to the remove function.

The key and its corresponding value are deleted from the HashMap, and the latest value stored against the key is returned.

Example 2

import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
// making a hashmap with keys as integers and strings as corresponding values
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
hash_map.put(10, "Ten");
hash_map.put(20, "Twenty");
hash_map.put(30, "Thirty");
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
// using the remove function with an existing key
String returned_value = (String)hash_map.remove(50);
// displaying the value returned by using existing key with remove function
System.out.println("Value Returned : " + returned_value);
// displaying the HashMap
System.out.println("Hash Map: " + hash_map);
}
}

In the above example, we pass an invalid key to the remove function. In this case, no changes occur in the map, and the remove function returns NULL.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved