Sunday, May 18, 2008

A better way to iterate java maps

Imagine you have a map like so

Map <Integer,String> map = new HashMap<Integer, String>();
map.put(0, "Value1");map.put(1, "Value2");

I often see code written in this fashion to Iterate over the map

Not so good code:

You can instead use the following code to iterate through each entry. A map is nothing but a series of Map.Entry objects. It is better to get a reference to Map.Entry and then iterate instead of getting all the keys and making the Map object do the work of fetching the value each time

Good code:

No comments: