Deleting a Key and its Value from HashMap in Java
In this tutorial, we'll see how to remove a specific key and its value from HashMap in Java by specifying the key or key-value pair.We'll use the remove(Object key) which removes the value of a specific key from the HashMap. If the key exists, the remove() method returns the element and removes the key-value pair.
import java.util.HashMap;Output:
public class remove_element_HashMap {
public static void main(String[] args) {
HashMapmap = new HashMap ();
map.put("value1",15);
map.put("value2",48);
map.put("value3",21);
map.put("value4",87);
map.put("value5",159);
map.put("value6",17);
System.out.println("Before removal: "+map);
Object elmDeleted = map.remove("value3");
System.out.println("the deleted item is "+elmDeleted);
System.out.println("Before "+elmDelete+": "+map) is removed;
}
}
Before removal: {value5=159, value6=17, value3=21, value4=87, value1=15, value2=48}
item deleted is 21
Before removing 21: {value5=159, value6=17, value4=87, value1=15, value2=48}