Balaguru Gupta wrote:Can anyone explain why Iterating a hashmap using Iterator is efficient than using foreach loop?
Why do you think that this is true? Because it isn't.
Note that a foreach loop will use an iterator "under the covers" - the compiler will generate code that loops over the map using an iterator. The foreach syntax is just to make it easier for you to write the code.
You should normally use the foreach loop syntax, because it's clearer and shorter to write. But if you need to remove elements from the map while you're iterating, you have to use the iterator syntax, because you need to be able to call remove() on the iterator, as you demonstrated in your code.