KeySet v EntrySet code tidy

Its astounding how often I find maps being used like this.

for(String name: names.keySet()) {
    mymap.put(mymap.get(name),name);
}

Its inefficient because you have to fetch the keys and perform a lookup in the map with the key.

Instead using the EntrySet you can get all the keys and values in one hit. This saves having to perform the map lookup.

for (Entry<String, String> entry : entrySet) {
    mymap.put(entry.getValue(),entry.getKey());
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

2 thoughts on “KeySet v EntrySet code tidy

  1. yeah, these mistakes are far too common. i have used findbugs in the past to flag these down