实例
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
//方法一:
for (Map.Entry<String, String> entry : map.entrySet()) {
//获取key值
String mapKey = entry.getKey();
//获取value值
String mapValue = entry.getValue();
//结果:key1:value1 key2:value2
System.out.println(mapKey + ":" + mapValue);
}
//方法二:
// 遍历获取key值
for (String key : map.keySet()) {
//结果 key1 key2
System.out.println(key);
}
// 遍历获取value值
for (String value : map.values()) {
//结果:value1 value2
System.out.println(value);
}
//方法三:
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Entry<String, String> entry = entries.next();
//获取key值
String key = entry.getKey();
//获取value值
String value = entry.getValue();
//结果:key1:value1 key2:value2
System.out.println(key + ":" + value);
}
//方法四:
//根据遍历得出的key值获取value值
for(String key : map.keySet()){
//获取value值
String value = map.get(key);
//结果:key1:value1 key2:value2
System.out.println(key+":"+value);
}
后记
for 和 Iterator的选择问题,在参考文章 迭代器Iterator与for循环的区别 中已经有详细的对比,如果想详细了解,可看参考文章内容