通过借鉴他人的文章整理出5种方式:
1.通过Map.KeySet遍历key和value
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("key: " + key + " value: " + value);
}
2.通过Map.entrySet使用iterator遍历key和value
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
3.通过Map.entrySet遍历key和value(推荐,尤其是容量大时:)
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
4.通过Map.values()遍历value,无法遍历key
for (String value : map.values()) {
System.out.println(" value: " + value);
}
5.通过Map.keySet()key,无法遍历value
for (String key : map.keySet()) {
System.out.println(" key: " + key);
}
No Best Code , Only Better Code。