Here are few ways to loop or iterate a Map or HashMap in Java.

package com.mkyong;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class LoopMap {
 
  public static void main(String[] args) {
 
	// initial a Map
	Map<String, String> map = new HashMap<String, 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");
 
	System.out.println("Example 1...");
	// Map -> Set -> Iterator -> Map.Entry -> troublesome
	Iterator iterator = map.entrySet().iterator();
	while (iterator.hasNext()) {
		Map.Entry mapEntry = (Map.Entry) iterator.next();
		System.out.println("The key is: " + mapEntry.getKey()
			+ ",value is :" + mapEntry.getValue());
	}
 
	System.out.println("Example 2...");
	// more elegant way
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("Key : " + entry.getKey() + " Value : "
			+ entry.getValue());
	}
 
	System.out.println("Example 3...");
	// weired way, but works anyway
	for (Object key : map.keySet()) {
		System.out.println("Key : " + key.toString() + " Value : "
			+ map.get(key));
	}
 
  }
 
}

Output

Example 1...
The key is: 3,value is :Mar
The key is: 2,value is :Feb
The key is: 1,value is :Jan
The key is: 6,value is :Jun
The key is: 5,value is :May
The key is: 4,value is :Apr
Example 2...
Key : 3 Value : Mar
Key : 2 Value : Feb
Key : 1 Value : Jan
Key : 6 Value : Jun
Key : 5 Value : May
Key : 4 Value : Apr
Example 3...
Key : 3 Value : Mar
Key : 2 Value : Feb
Key : 1 Value : Jan
Key : 6 Value : Jun
Key : 5 Value : May
Key : 4 Value : Apr
Note
Which ways to go? It’s your personal preference.
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts