Saturday, June 18, 2011

How to loop a Map in Java

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

package org.best.example.collection;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class LoopAMap{
 
   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");
 
 //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());
        }
 
        //more elegant way
        for (Map.Entry<String, String> entry : map.entrySet()) {
         System.out.println("Key : " + entry.getKey() 
          + " Value : " + entry.getValue());
        }
 
        //weired way, but work anyway
        for (Object key: map.keySet()) {
         System.out.println("Key : " + key.toString() 
          + " Value : " + map.get(key));
        }
 
   }
 
}

No comments: