geeky

Java: BETTER way to traverse a map

While reviewing the findbugs report (WMI_WRONG_MAP_ITERATOR) for a new project at work, I learned a better way to traverse a map in Java. In fact, since the first day I started coding in Java, I never thought twice about how to traverse a map. You always traverse the keys and use the key to get the value of the map.

for (Key key : map.keySet()) {
	Value value = map.get(key);
}

However, comes to think of it, it’s such a no-brainer. Every time you call map.get(key) you pay the price of the lookup. Since you need EVERY ELEMENT in the map, why look it up? Just get all of them like this:

for(Map.Entry mapEntry : map.entrySet()) {
	Key key = mapEntry.getKey();
	Value value = mapEntry.getValue();
}

That’s how jstl works. I just never paid attention. Better know it late than never πŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s