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.
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.
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:
import java.util.*;class HelloWorld {public static void main( String args[] ) {// making a hashmap with keys as integers and strings as corresponding valuesHashMap<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 HashMapSystem.out.println("Hash Map: " + hash_map);// using the remove function with an existing keyString returned_value = (String)hash_map.remove(20);// displaying the value returned by using existing key with remove functionSystem.out.println("Value Returned : " + returned_value);// displaying the HashMapSystem.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.
import java.util.*;class HelloWorld {public static void main( String args[] ) {// making a hashmap with keys as integers and strings as corresponding valuesHashMap<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 HashMapSystem.out.println("Hash Map: " + hash_map);// using the remove function with an existing keyString returned_value = (String)hash_map.remove(50);// displaying the value returned by using existing key with remove functionSystem.out.println("Value Returned : " + returned_value);// displaying the HashMapSystem.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