Thursday, December 10, 2009

Why use Map.entrySet() instead of Map.keySet()?

(From http://www.coderanch.com/t/382487/Java-General/java/Why-use-Map-entrySet)

If you just need keys, use keySet(). If you just need values, use values(). If you're going to use keys and values in your subsequent code, then you're best off using entrySet().

I frequently see people do this without entrySet(), and it usually looks something like this:

for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
Foo key = (Foo) it.next();
Bar value = (Bar) map.get(key);
// now do something with key and value
}

This works, but it's making the JVM do extra work for no good reason. Every time you call get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and evaluating a comparator. These operations may be fast, or not, but why do them if you don't have to? A Map.Entry gives you both key and value, together, in the most efficient manner possible.

for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry e = (Map.Entry) it.next();
Foo key = (Foo) e.getKey();
Bar value = (Bar) e.getValue();
// now do something with key and value
}


Under JDK 5 and later it's a little nicer:

for (Map.Entry e : map.entrySet()) {
Foo key = e.getKey();
Bar value = e.getValue();
// now do something with key and value
}

No comments: