以下通过程序来简单实践一下HashMap的的遍历

PS:如果要保持HashMap的遍历顺序和原插入顺序一致,可以使用LinkedHashMap,使用方法和HashMap一样,改一下声明即可:LinkedHashMap myMap = new LinkedHashMap(); 当然需要导入:java.util.LinkedHashMap

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapList {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  HashMap myMap = new HashMap();
  
  myMap.put("hello", "你好");
  myMap.put("bye", "再见");
  myMap.put("thanks", "谢谢");
  myMap.put("ok", "好的");
  
  System.out.println("--------------------遍历key和value----------------------");
  for(Iterator iter = myMap.entrySet().iterator();iter.hasNext();){
            Map.Entry element = (Map.Entry)iter.next();
            Object strKey = element.getKey();
            Object strObj = element.getValue();
           
            System.out.println("myMap.get(\""+strKey+"\")="+strObj);
  }
  
  System.out.println();
  System.out.println("--------------------遍历整个HashMap----------------------");
  Collection objs = myMap.entrySet();
  for (Iterator iterator=objs.iterator(); iterator.hasNext();){
   Object obj = iterator.next();
   System.out.println(obj);
  }
  
  System.out.println();
  System.out.println("--------------------遍历HashMap的key----------------------");
  Collection keys = myMap.keySet();
  for (Iterator iterator=keys.iterator(); iterator.hasNext();){
   Object key = iterator.next();
   System.out.println(key);
  }
  
  System.out.println();
  System.out.println("--------------------遍历HashMap的value----------------------");
  Collection values = myMap.values();
  for (Iterator iterator=values.iterator(); iterator.hasNext();){
   Object value = iterator.next();
   System.out.println(value);
  }
 }
}

运行结果
--------------------遍历key和value----------------------
myMap.get("hello")=你好
myMap.get("thanks")=谢谢
myMap.get("ok")=好的
myMap.get("bye")=再见

--------------------遍历整个HashMap----------------------
hello=你好
thanks=谢谢
ok=好的
bye=再见

--------------------遍历HashMap的key----------------------
hello
thanks
ok
bye

--------------------遍历HashMap的value----------------------
你好
谢谢
好的
再见