Removing an Entry from a Java HashMap
How to Remove an Entry from a Java HashMap
The HashMap class in Java is one of the most commonly used collections. It is a powerful data structure that offers fast access to objects stored in the map. The HashMap class also allows users to easily add, update, and remove entries from the map. In this tutorial, we’ll look at how to remove an entry using the Java HashMap remove() method.
HashMap remove() Method
The Java HashMap remove() method is used to remove a key/value pair from the map. The method accepts two parameters, the key and its corresponding value. If the key doesn’t exist in the map, the method will return null. On the other hand, if the key is present in the map, it will remove the corresponding value and return the value.
// remove a value from the map
Object value = map.remove(key);
In addition to the remove() method, the HashMap class also provides the removeIf() method which can be used to delete entries from the map based on a certain condition. We’ll look at how to use this method in the next section.
HashMap removeIf() Method
The Java HashMap removeIf() method is used to remove entries from the map based on a predefined condition. The method accepts a predicate as a parameter which is used to test the elements of the map and remove them if the condition is satisfied. The method returns true if the map is modified after the removal.
// remove all entries with value greater than 10
map.removeIf(entry -> entry.getValue() > 10);
And that’s it! We’ve seen how to use the Java HashMap remove() and removeIf() methods to delete entries from the map. Understanding how to use these methods can be invaluable in building efficient and powerful applications.