In this article we will discuss different ways to remove elements from HashMap while Iterating.

Let’s create a HashMap of String as Key and Integer as value and add some elements into it i.e.

Now lets remove elements from this HashMap while iterating using 2 different techniques

Remove elements from HashMap while Iterating using KeySet

keyset() method of HashMap returns a set of keys in the HashMap and its backed by HashMap i.e. any items removed from the Key Set will be removed from HashMap too.

So lets Iterate over the HashMap using KeySet Iterator and remove all the elements whose value is ODD, while Iterating i.e.

Remove elements from Hahsmap while Iterating using EntrySet

HashMap member function entrySet() returns a set of Entry<K,V> in the HashMap and its backed by HashMap i.e. any items remover from the Entry Set will be removed from HashMap too.

So lets Iterate over the HashMap using Entry Set Iterator and remove all the elements whose value is 10 while Iterating i.e.

Complete example is as follows,

Output

HashSet

Java Interview Questions

Click Here to Subscribe for more Articles / Tutorials like this.