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