java8 Map 的compute的用法


介紹

compute是java8 Map接口帶來的默認接口函數, 其他相關函數computeIfPresent computeIfAbsent

compute

源碼如下, 1. newValue替換oldValue,返回newValue
2. 如果newValue==null則剔除元素

//源碼
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;
    }
}

示例一、統計數組中每個數的出現次數

Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 1, 1, 2, 3};
Arrays.asList(arr).forEach(element -> {
    map.compute(element, (k, v) -> {
        if (v == null) {
            return 1;
        } else {
            return v + 1;
        }
    });
});

示例二、刪除某個元素

Arrays.asList(arr).forEach(element -> {
    map.compute(element, (k, v) -> {
        return null;
    });
});

computeIfAbsent

源碼如下。1. value!=null直接返回,value==null通過mappingFunction得到新值返回

default V computeIfAbsent(K key,
      Function<? super K, ? extends V> mappingFunction) {
  Objects.requireNonNull(mappingFunction);
  V v;
  if ((v = get(key)) == null) {
      V newValue;
      if ((newValue = mappingFunction.apply(key)) != null) {
          put(key, newValue);
          return newValue;
      }
  }

  return v;
}

示例一、map給未賦值的key賦值

Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 2, 3};
map.put(1, 1);
Arrays.asList(arr).forEach(key -> {
    map.computeIfAbsent(key, k -> {
        return k;
    });
});

computeIfPresent

源碼如下。1. value!=null根據remappingFunction得到新值,value==null則返回null

default V computeIfPresent(K key,
        BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    Objects.requireNonNull(remappingFunction);
    V oldValue;
    if ((oldValue = get(key)) != null) {
        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue != null) {
            put(key, newValue);
            return newValue;
        } else {
            remove(key);
            return null;
        }
    } else {
        return null;
    }
}

示例一、map給已存在的key value + 1

Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 2, 3};
map.put(1, 1);
Arrays.asList(arr).forEach(key -> {
    map.computeIfPresent(key, (k, v) -> {
        return v + 1;
    });
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM