Map map = new HashMap<>();
map.put("name", "Alice");
map.put("age", "25");
// Java 8+ Lambda (最簡潔)
map.forEach((key, value) -> System.out.println(key + " = " + value));
// 傳統 Iterator
for (Iterator> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = it.next();
String key = entry.getKey();
String val = entry.getValue();
System.out.println(key + " = " + val);
}
// 增強 for (底層同 Iterator)
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
for (String key : map.keySet()) {
String val = map.get(key); // 額外 hash 查找
System.out.println(key + " = " + val);
}
// Iterator 版
for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
String key = it.next();
String val = map.get(key);
}
for (String val : map.values()) {
System.out.println(val);
}
| 方式 | 時間複雜度 | 實際開銷 | 適用場景 |
|---|---|---|---|
| entrySet | O(n) | 1 次遍歷,直接取 Entry | 需同時用到 key & value (最常見) |
| keySet + get | O(n) 但常數大 | n 次額外 hash 計算 & 桶定位 | 極少,僅教學展示 |
| values | O(n) | 1 次遍歷,僅取 value | 完全不需要 key |
entrySet() 返回 Set,每個 Entry 直接持有 key/value 引用,遍歷時無需再次查找 keySet() 只持有 key,map.get(key) 需重新計算 hash(key)、定位桶、遍歷鏈表/紅黑樹Node<K,V> 即實現 Map.Entry<K,V>,entrySet 近乎零開銷// 1. Collections.synchronizedMap — 需手動同步整個遍歷
Map syncMap = Collections.synchronizedMap(new HashMap<>());
synchronized (syncMap) {
for (var entry : syncMap.entrySet()) { ... }
}
// 2. ConcurrentHashMap — 弱一致性迭代器,無需鎖
ConcurrentHashMap ccMap = new ConcurrentHashMap<>();
ccMap.forEach((k, v) -> ...); // 安全,可能不反映最新狀態
// 3. CopyOnWriteMap — 遍歷快照,完全隔離寫入
// 適合讀多寫極少場景
// 過濾 + 轉換
map.entrySet().stream()
.filter(e -> e.getKey().startsWith("a"))
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
// 收集為 List
List keys = map.keySet().stream().collect(Collectors.toList());
// 轉為另一 Map
Map lengths = map.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().length()
));
// 並行流 (大數據量)
map.entrySet().parallelStream().forEach(...);
map.put/remove 拋 ConcurrentModificationException。解決:Iterator.remove()、收集待刪 key 後批次刪、或用 ConcurrentHashMap90% 場景用 entrySet (或 forEach) 最優。僅需 value 用 values()。避免 keySet + get。並發環境選 ConcurrentHashMap + forEach。