public static void main(String[] args){ Map<String, String> map = new HashMap();
map.put("郑州", "河南"); map.put("长沙", "湖南");
//method one Set<String> set = map.keySet();
for (String key:set) { System.out.println(s+","+map.get(key)); }
//method two Set<Map.Entry<String, String>> entryseSet=map.entrySet();
for (Map.Entry<String, String> entry:entryseSet) { System.out.println(entry.getKey()+":"+entry.getValue()); }
//method three
Iterator it = map.keySet().iterator();
while(it.hasNext()){
int key = (Integer) it.next();
String value = map.get(key);
}
}
其中第一种方法和第三种在本质上来说是相似的,只是第三种在第一种的基础上加了个迭代器。 个人推荐第二种。
本文介绍了使用Java遍历Map集合的三种方法,并对比了它们之间的差异。第一种和第三种方法本质上相似,但第三种引入了迭代器。作者推荐使用第二种方法。
747





