Simplest way to iterate through a Java HashMap

Lets say  you have a map that looks like this….

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

Now the simplest way to iterate through this map is as follows…

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println ("k=" + entry.getKey() + ", v=" + entry.getValue());
}

The output looks like this…

k=0, v=apple
k=1, v=orange
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