Java HashMap.remove()
In this tutorial, we will learn about the Java HashMap.remove() function, and learn how to use this function to remove a key-value mapping from this HashMap, with the help of examples.
remove()
HashMap.remove() removes the mapping for the specified key from this map, if present, and returns the previously associated value for this key.
If the key is not already present, remove() returns null.
The syntax of remove() function is
remove(key)
where
Parameter | Type | Description |
---|---|---|
key | Object | The key for which we would like to remove the mapping in this HashMap. |
Returns
The function returns the value associated with the key.
Examples
1. remove(key) basic example
In this example, we will initialize a HashMap hashMap
with some mappings in it. We will remove the key-value mapping for the key 3
in this HashMap using remove() method. Since, the key 3
is present in this HashMap, remove() returns the value corresponding to this key.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
hashMap.put(4, "D");
System.out.println("HashMap before remove : " + hashMap);
int key = 3;
String value = hashMap.remove(key);
System.out.println("HashMap after remove : " + hashMap);
System.out.println("remove() returned value : " + value);
}
}
Output
HashMap before remove : {1=A, 2=B, 3=C, 4=D}
HashMap after remove : {1=A, 2=B, 4=D}
remove() returned value : C
2. remove(key) when key is not present in HashMap
In this example, we will initialize a HashMap hashMap
with some mappings in it. We will remove the key-value mapping for the key 5
in this HashMap using remove() method. Since, the key 5
is not present in this HashMap, remove() does nothing to this HashMap and returns null
value.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
hashMap.put(4, "D");
System.out.println("HashMap before remove : " + hashMap);
int key = 5;
String value = hashMap.remove(key);
System.out.println("HashMap after remove : " + hashMap);
System.out.println("remove() returned value : " + value);
}
}
Output
HashMap before remove : {1=A, 2=B, 3=C, 4=D}
HashMap after remove : {1=A, 2=B, 3=C, 4=D}
remove() returned value : null
Conclusion
In this Java Tutorial, we have learnt the syntax of Java HashMap.remove() function, and also learnt how to use this function with the help of examples.