首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Map 遍歷三種主流寫法:keySet、entrySet 與 Iterator 完整對比

     編輯:Java 相關知識

前言

Map 遍歷是日常開發高頻操作。本文對比三種主流寫法的語法、效能、適用場景,並給出最佳實務建議。

1. keySet + get(不推薦高頻)

Map map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);

// 僅需 Key 時
for (String key : map.keySet()) {
    System.out.println(key);
}

// 需 Key+Value:兩次查找,效能較差
for (String key : map.keySet()) {
    Object val = map.get(key); // 額外 hash 查找
    System.out.println(key + "=" + val);
}

2. entrySet(推薦標準寫法)

// Java 8+ Lambda
map.forEach((k, v) -> System.out.println(k + "=" + v));

// 傳統 for-each
for (Map.Entry entry : map.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

// 需修改 Value
for (Map.Entry entry : map.entrySet()) {
    entry.setValue(entry.getValue() + "_new");
}

3. Iterator(舊版本/需安全刪除)

Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry entry = it.next();
    System.out.println(entry.getKey() + "=" + entry.getValue());
    // 安全刪除
    if (entry.getValue().equals("removeMe")) {
        it.remove();
    }
}

4. 效能微基準(JMH 參考)

寫法相對耗時 (ns/op)備註
entrySet for-each1.0x基準,最快
forEach Lambda1.1x極微小開銷
keySet + get1.8x雙重查找
Iterator1.05x與 entrySet 相近

5. 並發環境下的遍歷

  • ConcurrentHashMap:支援弱一致性迭代器,遍歷期間允許並發修改,不拋 ConcurrentModificationException。
  • Collections.synchronizedMap:遍歷必須鎖定整個 Map:
Map syncMap = Collections.synchronizedMap(new HashMap<>());
synchronized (syncMap) {
    for (Map.Entry e : syncMap.entrySet()) {
        // ...
    }
}

6. Java 8 Stream 進階用法

// 過濾並轉 List
List keys = map.entrySet().stream()
    .filter(e -> e.getValue() instanceof Integer)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

// 分組統計
Map freq = map.values().stream()
    .collect(Collectors.groupingBy(v -> v, Collectors.counting()));

7. 總結建議

  1. 唯讀遍歷 → entrySet for-each 或 forEach Lambda。
  2. 需刪除 → Iterator.remove() 或 removeIf(Java 8)。
  3. 僅需 Key → keySet()。
  4. 高併發 → ConcurrentHashMap 弱一致性迭代器。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved