遍歷 Map 是日常開發中極高頻的操作。Java 提供了多種遍歷路徑,各有適用場景與效能差異。本文整理三種主流寫法,並附上可直接執行的範例程式碼。
Map map = new HashMap<>();
map.put("1001", new Student("宋江", "1001", 38));
map.put("1002", new Student("盧俊義", "1002", 35));
map.put("1003", new Student("吳用", "1003", 34));
// ... 略
public static void work(Map map) {
Collection values = map.values();
Iterator it = values.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
優點:語法簡單,適合「只關心值、不需要鍵」的場景。
缺點:無法獲取鍵,若後續需根據鍵操作則不適用。
public static void workByKeySet(Map map) {
Set keySet = map.keySet();
for (Iterator it = keySet.iterator(); it.hasNext(); ) {
String key = it.next();
System.out.println(map.get(key));
}
}
優點:可同時獲取鍵與值,靈活度高。
缺點:每次迭代需額外呼叫 map.get(key),有輕微效能開銷。
public static void workByEntry(Map map) {
Set> entrySet = map.entrySet();
for (Iterator> it = entrySet.iterator(); it.hasNext(); ) {
Map.Entry entry = it.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
}
優點:一次迭代直接拿到鍵值對,避免二次查找,效能最佳。
適用:需同時處理鍵與值的大多數業務場景。
// Lambda 簡潔風格
map.forEach((k, v) -> System.out.println(k + "=" + v));
// Stream API 處理複雜邏輯
map.entrySet().stream()
.filter(e -> e.getValue().getAge() > 30)
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
| 場景 | 推薦方式 |
|---|---|
| 僅需值 | values() / forEach |
| 需鍵值對、高頻遍歷 | entrySet() |
| 需對鍵單獨操作(如刪除) | keySet() 配合 Iterator.remove() |