• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inefficient use of keySet iterator instead of entrySet iterator  RSS feed

 
Sam Saha
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am using Keyset iterator in my code. I am getting a complaint like “Inefficient Use of ketSet iterator instead of entrySet iterator”. I would appreciate if someone can help me to resolve this issue. Thank you very much.
I am Getting complaing the line String val = (String)aMap.get(key);

 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see you are using a while loop. For any collections (lists, sets, maps) and arrays, it is wise to use the foreach loop.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is why you get that message: In your code you're iterating over a map. You iterate over the keys (by getting the key set of the map). But for each iteration, you also want to get the value for that key (that's what you're doing in line 5).

So, for each iteration, you're doing a lookup in the map. That's unnecessarily inefficient.

Instead of iterating over the keys and then getting the value for each key, it is more efficient to iterate over the entries (key-value pairs) of the map, by iterating over the entry set. Each entry will contain the key and the value for that key - you get the value immediately from the entry, it doesn't need to be looked up in the map.

And ofcourse it's a good idea to use a for-each style loop as K. Tsang shows, because it makes your code easier to understand.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!