Iterating over Map’s

A lot of times, i have come across the following code for iterating over a Map

Map values=new HashMap();
Setkeys=values.keySet();
for(Integer key:keys){
String val=values.get(key);
}
A better way is
Map values=new HashMap();
Setkeys=values.keySet();
for(Map.Entryentry:values.entrySet()){
String val=entry.getValue();
}
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

Advertisements

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

%d bloggers like this: