1.功能簡介
簡單的說就是,給出一個key值和一個函數,然后這個函數根據key對應的鍵值對[key,value]計算出一個新的value,就叫newValue吧
如果這個newValue的值是null,則從原來的map中移除key,compute返回null,
如果這個newValue的值不為null,則更新key對應的值為newValue,compute返回newValue。
2.應用例子
// 統計一個字符串中每個字符出現的次數
public static void main(String[] args) { Map<Character, Integer> map = new HashMap<>(); String hello = "Hello World!"; for (int i = 0; i < hello.length(); i++) { char key = hello.charAt(i); map.compute(key, (k, v) -> { if (Objects.isNull(v)) { v = 1; } else { v += 1; } return v; }); } System.out.println(map.toString()); }
輸出
{ =1, !=1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
3.JDK中的源碼:
default V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue = get(key); V newValue = remappingFunction.apply(key, oldValue); if (newValue == null) { // delete mapping if (oldValue != null || containsKey(key)) { // something to remove remove(key); return null; } else { // nothing to do. Leave things as they were. return null; } } else { // add or replace old mapping put(key, newValue); return newValue; } }