Java HashMap - remove() Method
The java.util.HashMap.remove() method is used to remove the entry for the specified key only if it is currently mapped to the specified value.
Syntax
public boolean remove(Object key, Object value)
Parameters
key |
Specify key with which the specified value is associated. |
value |
Specify value expected to be associated with the specified key. |
Return Value
Returns true if the value was removed.
Exception
NA.
Example:
In the example below, the java.util.HashMap.remove() method is used to remove the mapping for the specified key from the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a hash map HashMap<Integer, String> MyMap = new HashMap<Integer, String>(); //populating MyMap MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); //printing MyMap System.out.println("Before remove, MyMap contains: " + MyMap); //remove mapping for 102 key MyMap.remove(102, "Marry"); //remove 103 key - with no effect as //the specified value is not matching MyMap.remove(103, "Sam"); //printing MyMap System.out.println("After remove, MyMap contains: " + MyMap); } }
The output of the above code will be:
Before remove, MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo} After remove, MyMap contains: {101=John, 103=Kim, 104=Jo}
❮ Java.util - HashMap