javacodex.com
Java Examples
Java Examples
memu home questions

Iterate Through A HashMap

This java example shows how to iterate through a HashMap.

Source: (IteratorExample.java)

import java.util.*;
 
public class IteratorExample {
   public static void main(String[] args) {
      HashMap<Integer, String> map = new HashMap<Integer, String>();
      map.put( new Integer(1), "Tom Brady" );
      map.put( new Integer(2), "Tom Cruise" );
      map.put( new Integer(3), "Tom Hanks" );
      map.put( new Integer(4), "Tom Sawyer" );
 
      // Using Iterator
      Iterator<Integer> it = map.keySet().iterator();
      while(it.hasNext()){
         Integer key = it.next();
         System.out.println(key + " : " + map.get(key));
      }
 
      // For Loop
      for (Integer key : map.keySet()) {
         System.out.println(key + " : " + map.get(key));
      }
 
   }
}

Output:

$ java IteratorExample 
1 : Tom Brady
2 : Tom Cruise
3 : Tom Hanks
4 : Tom Sawyer
1 : Tom Brady
2 : Tom Cruise
3 : Tom Hanks
4 : Tom Sawyer

Contact: javacodex@yahoo.com