compute
和computeIfAbsent
都是Map
接口中的默認方法,用于在映射中進行鍵值對的計算和更新。它們的主要區別在于它們的行為和使用場景。
compute
方法
定義:
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction);
-
參數:
key
: 要計算其值的鍵。remappingFunction
: 用于計算新值的函數。它接受兩個參數:鍵和當前值(如果鍵不存在,則當前值為null
),并返回一個新值。
-
行為:
- 如果鍵存在,
remappingFunction
會應用于當前鍵和值,并返回一個新的值。 - 如果鍵不存在,
remappingFunction
會應用于鍵和null
,并返回一個新的值。 - 如果
remappingFunction
返回null
,則從映射中刪除該鍵。
- 如果鍵存在,
示例
import java.util.HashMap;
import java.util.Map;public class ComputeExample {public static void main(String[] args) {Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.put("b", 2);// 使用 compute 更新已存在的值map.compute("a", (k, v) -> v == null ? 42 : v + 1);// 使用 compute 添加新值map.compute("c", (k, v) -> v == null ? 42 : v + 1);System.out.println(map); // 輸出: {a=2, b=2, c=42}}
}
computeIfAbsent
方法
定義:
V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction);
-
參數:
key
: 要計算其值的鍵。mappingFunction
: 用于計算新值的函數。它接受一個參數:鍵,并返回一個新值。
-
行為:
- 如果鍵不存在,則
mappingFunction
會被調用來計算一個值,并將這個值與鍵關聯。 - 如果鍵已經存在,則不會調用
mappingFunction
,直接返回當前值。
- 如果鍵不存在,則
示例
import java.util.HashMap;
import java.util.Map;public class ComputeIfAbsentExample {public static void main(String[] args) {Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.put("b", 2);// 使用 computeIfAbsent 添加新值map.computeIfAbsent("c", k -> 42);// 使用 computeIfAbsent 不會更新已存在的值map.computeIfAbsent("a", k -> 42);System.out.println(map); // 輸出: {a=1, b=2, c=42}}
}
區別總結
-
compute
:- 適用于需要根據鍵和值計算新值的情況。
- 即使鍵不存在,也會調用計算函數。
- 可以用于更新和刪除鍵值對。
-
computeIfAbsent
:- 適用于僅在鍵不存在時計算新值的情況。
- 如果鍵已經存在,不會調用計算函數。
- 只能用于添加新鍵值對,不會更新已存在的鍵值對。
用法對比
import java.util.HashMap;
import java.util.Map;public class ComputeVsComputeIfAbsent {public static void main(String[] args) {Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.put("b", 2);// 使用 compute 更新已存在的值map.compute("a", (k, v) -> v == null ? 42 : v + 1);// 使用 computeIfAbsent 添加新值map.computeIfAbsent("c", k -> 42);System.out.println(map); // 輸出: {a=2, b=2, c=42}// 使用 computeIfAbsent 不會更新已存在的值map.computeIfAbsent("a", k -> 42);System.out.println(map); // 輸出: {a=2, b=2, c=42}// 使用 compute 更新已存在的值map.compute("a", (k, v) -> v == null ? 42 : v + 1);System.out.println(map); // 輸出: {a=3, b=2, c=42}}
}
通過這些示例,可以清楚地看到compute
和computeIfAbsent
的不同用法和行為。