Introduction
In Java, Map is an interface part of the Collection framework that is used to collect elements into key and value pairs. In this step-by-step lab, you will learn how to remove an element from a Java Map.
In Java, Map is an interface part of the Collection framework that is used to collect elements into key and value pairs. In this step-by-step lab, you will learn how to remove an element from a Java Map.
To remove an element from the map, we first need to create a Java Map. In this step, we use HashMap to create a map and add some elements to it:
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 65);
map.put("B", 66);
map.put("C", 67);
map.put("D", 68);
map.put("E", 69);
System.out.println("Original Map: " + map);
}
}
remove()
We can use the remove()
function to remove an element from the map by specifying the key of the element we want to remove. The remove()
function will return the value of the removed element. Here is an example:
int removedValue = map.remove("D");
System.out.println("Removed Element Value: " + removedValue);
System.out.println("Map after removing element: " + map);
remove(key, value)
The remove(key, value)
function removes the element only if both the specified key and value are present in the map. The function will return true
if both the key and value are present in the map, otherwise, it returns false
. Here is an example:
boolean isElementRemoved = map.remove("D", 68);
System.out.println("Is Element Removed? " + isElementRemoved);
System.out.println("Map after removing element: " + map);
replace()
Instead of removing an element and then adding a new one, we can use the replace()
function to replace an element in the map. The replace()
function replaces the key-value pair of the specified key with the specified value. Here is an example:
map.replace("D", 90);
System.out.println("Map after replacing element: " + map);
replace(key, oldValue, newValue)
The replace(key, oldValue, newValue)
function replaces the value of the specified key only if the current value is equal to the specified old value. Here is an example:
map.replace("D", 68, 5);
System.out.println("Map after replacing element: " + map);
To run the code, open the terminal, navigate to the directory where the code file is and run the following command to compile and run the code:
javac Main.java && java Main
You will see the output for each step in the terminal.
In this lab, you have learned how to remove an element from the Java Map using different techniques. You can now modify and remove elements from the Java Map using the remove() and replace() functions by specifying the key and value of the element.