Beginning from Java 8, the Map
interface includes the remove(Object key, Object value)
method, which removes the entry for the specified key only if it is currently mapped to the specified value.
Here is a Java 8 way of accomplishing this:
package org.kodejava.util;
import java.util.HashMap;
import java.util.Map;
public class MapRemoveKeyValueExample {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<>();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
System.out.println("Map before: " + myMap);
myMap.remove("key1", "value1");
System.out.println("Map after: " + myMap);
}
}
Output:
Map before: {key1=value1, key2=value2}
Map after: {key2=value2}
It’s important to note, however, that this method will do nothing if the initially passed value does not match the value currently mapped by the key in the map. The method also returns a boolean indicating whether the removal was successful (i.e., the key/value pair was in the map).
The remove(Object key, Object value)
method is indeed a more concise way to accomplish this task in Java 8 or above, as it does not require an explicit condition check as in the previous approach.
Latest posts by Wayan (see all)
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024