public void loopMapByKeySet() {
Map testMap = new HashMap<>();
testMap.put("testKey1", 1);
testMap.put("testKey2", 2);
testMap.put("testKey3", 3);
for (String key : testMap.keySet()) {
System.out.print("key : " + key + " , value : " + testMap.get(key));
}
}
这种方式代码逻辑清晰,但有个很严重的问题是效率低。
public void loopMapByIterator() {
Map testMap = new HashMap<>();
testMap.put("testKey1", 1);
testMap.put("testKey2", 2);
testMap.put("testKey3", 3);
Iterator> iterator = testMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.print("key : " + entry.getKey() + " , value : " + entry.getValue());
}
}
这种方式效率较高,但是对不熟悉Iterator的人阅读起来稍微有点不友好。
public void loopMapByEntrySet() {
Map testMap = new HashMap<>();
testMap.put("testKey1", 1);
testMap.put("testKey2", 2);
testMap.put("testKey3", 3);
for (Map.Entry entry : testMap.entrySet()) {
System.out.print("key : " + entry.getKey() + " , value : " + entry.getValue());
}
}
这种方式本质跟方法二没区别,只是改进了下写法,不仅效率高,代码也简洁了一些,阅读起来更友好。