Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterating a hashmap using Iterator is efficient than using foreach loop

 
Balaguru Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain why Iterating a hashmap using Iterator is efficient than using foreach loop?
 
Muneeswaran Balasubramanian
Ranch Hand
Posts: 138
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Balaguru,


Foreach loop only used for Iteration.That means readonly.

But using iterator we can modify the collection using the method remove of Iterator.

This point add the value to your post.Waiting for others quotes,,,,,
 
Balaguru Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Muneeswaran,

I worked out with the same.
Example program ,

Apart from this reason, Is there any other difference for the same to justify that Iterator is efficient than foreach loop?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15490
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Balaguru Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Jesper de Jong,

Thank you so much. Now I am pretty much clear with the concept and difference between using Iterator and foreach.

Cheerz mate
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic