Map remove() Method in Java with Examples
Last Updated :
11 Jul, 2024
Improve
The map.remove() method is used to remove the mapping for a key from this map if it is present in the map.
Syntax:
V remove(Object key)
- Parameters: This method has the only argument key, whose mapping is to be removed from the map.
- Returns: This method returns the value to which this map previously associated the key, or null if the map contained no mapping for the key.
- Time Complexity: Average time complexity of O(1) and a worst-case time complexity of O(n).
Map remove() Method in Java
Example 1: The below programs show the implementation of the map.remove() method.
// Java code to show the implementation of
// remove method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(3, "Three");
map.put(5, "Five");
map.put(7, "Seven");
map.put(9, "Nine");
System.out.println(map);
map.remove(3);
System.out.println(map);
// If it doesn't exists, returns
// null and does not affects the map
map.remove(2);
System.out.println(map);
}
}
Output
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine} {1=One, 5=Five, 7=Seven, 9=Nine} {1=One, 5=Five, 7=Seven, 9=Nine}
Explanation of the Program:
- This example demonstrates the use of the
remove
method in theMap
interface using aHashMap
. - It initializes a
HashMap
with integer keys and string values, then removes the entry with key3
, and attempts to remove a non-existent key2
. - The output shows the map before and after the removals, illustrating how the
remove
method works and that attempting to remove a non-existent key has no effect on the map.
Example 2: Below is the code to show implementation of put().
// Java code to show the implementation of
// remove method in Map interface
import java.util.*;
public class GfG {
// Driver code
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("3", "Three");
map.put("5", "Five");
map.put("7", "Seven");
map.put("9", "Nine");
System.out.println(map);
map.remove("3");
System.out.println(map);
}
}
Output
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine} {1=One, 5=Five, 7=Seven, 9=Nine}
Explanation of the Program:
- This program demonstrates the use of the
remove
method in theMap
interface using aHashMap
. - It also initializes a
HashMap
with string keys and values, prints the map, removes the entry with key"3"
, and then prints the map again to show the result of the removal. - The output illustrates how the
remove
method affects the map by removing the specified key-value pair.