Tuesday 25 February 2014

Java: Iterating through the Map

This example demonstrates different way of iterating or looping through a Map-HashMap. Folling topics are covered

  1. Iterating through the Map using iterator
  2. Iterating through the Map keys
  3. Iterating through the Map values
  4. Iterating using a for loop

public class MapIteration
{
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Jan");
map.put(2, "Feb");
map.put(3, "Mar");
map.put(4, "Apr");
map.put(5, "May");
map.put(6, "Jun");

Iterator<Entry<Integer, String>> iter = map.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry<Integer, String> mapEntry = (Map.Entry<Integer, String>) iter.next();
System.out.println("Key: " + mapEntry.getKey() + ", Value :" + mapEntry.getValue());
}

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

Iterator keysIter = map.keySet().iterator();
while (keysIter.hasNext())
{
Integer key = (Integer) keysIter.next();
System.out.println("Key: " + key);
}

for (String value : map.values())
{
System.out.println("Value : " + value);
}
}
}

No comments:

Post a Comment