How do I remove entry from Java Map
without using iteration using value or key. Basically in my map, I am using containsKey()
then map.remove()
to remove it.
HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.
While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry. getKey() method. If the key matches, remove the entry of that iteration from the HashMap using remove() method.
Assuming your set contains the strings you want to remove, you can use the keySet method and map. keySet(). removeAll(keySet); . keySet returns a Set view of the keys contained in this map.
The java. util. HashMap. clear() method in Java is used to clear and remove all the elements or mappings from a specified HashMap.
In most cases you can remove entry (key-value pair) from a map using Map.remove(key)
method. There will be no iteration over the map. You don't need to use Map.containsKey(key)
before the Map.remove(key)
because Map.remove
already does it. It returns either a previous associated value with key
or null
if there was no mapping for the key
.
But you can't do the same thing using a value only (without key). The only option is to iterate via map and find entry (or entries) with that value.
Java 5-7:
for (Iterator<MyValue> it = map.values.iterator(); it.hasNext(); ) {
if(it.next().equals(myValue)) {
it.remove();
}
}
Java 8:
map.values().removeIf(v -> v.equals(myValue));
Use Map#remove(Object key)
:
public V remove(Object key)
Removes the mapping for this key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that
(key==null ? k==null : key.equals(k))
, that mapping is removed. (The map can contain at most one such mapping.)Returns the value to which the map previously associated the key, or null if the map contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) The map will not contain a mapping for the specified key once the call returns.
Basically you can call remove, even if the key does not exist. It will silently fail in that case(returning null). The object need not be identical or the same, if yourKey.equals(key)
is true for the key you want to remove.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With