computeIfAbsent

若key对应的value为空,会将第二个参数的返回值存入并返回。

  1. // 方法定义
  2. default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
  3. ...
  4. }
  5. // java8之前。从map中根据key获取value操作可能会有下面的操作
  6. Object key = map.get("key");
  7. if (key == null) {
  8. key = new Object();
  9. map.put("key", key);
  10. }
  11. // java8之后。上面的操作可以简化为一行,若key对应的value为空,会将第二个参数的返回值存入并返回
  12. Object key2 = map.computeIfAbsent("key", k -> new Object());
  1. (map, words) -> {
  2. for (String word : words) {
  3. // 注意不能使用 putIfAbsent,此方法返回的是上一次的 value,首次调用返回 null
  4. map.computeIfAbsent(word, (key) -> new LongAdder()).increment();
  5. }
  6. }

putIfAbsent

  • 使用put方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null,如果已经存在对应的值,则会覆盖旧值,value为新的值。
  • 使用putIfAbsent方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null,如果已经存在对应的值,则依旧为原来的值。