How to remove elements from HashMap

To remove elements from HashMap we can use either of the 2 ways
1. Use the remove(Object key) method
2. Remove elements while iterating the HashMap

Lets see some examples for both these ways

1. Use the remove(Object key) to remove elements from HashMap

remove(Object key) method removes the mapping of the key/value from the HashMap and return the previous value that was removed.
Please note if the remove() method returns a null value, that doesn’t necessarily mean that no object/element was removed. This would be a case where a key with NULL value was stored in the HashMap.

Output

2. Use the Iterator to remove elements from HashMap

Iterator can be also used to remove all or a specific element from HashMap

Reference

1. HashMap

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn