前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ConcurrentMap的Method

ConcurrentMap的Method

作者头像
WindCoder
发布2020-01-21 16:39:28
7620
发布2020-01-21 16:39:28
举报
文章被收录于专栏:WindCoderWindCoderWindCoder

暂且仅记录方法:computecomputeIfAbsentcomputeIfPresentputIfAbsent

基础

Method

形式

描述

实例

功能特性

compute

default V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

尝试计算指定key及其当前映射值的映射(如果没有当前映射,则为null)。

map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))

新增/替换更新

computeIfAbsent

default V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

如果指定的key尚未与值相关联(或映射到null),则尝试使用给定的映射函数计算其值,并将其输入到此映射中,除非为null。

map.computeIfAbsent(key, k -> new Value(f(k)));

新增

computeIfPresent

default V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)

如果指定key的值存在且非空,则尝试计算给定key及其当前映射值V的新映射。

map.computeIfPresent(1, (key, value) -> (key + 1) + value);

替换更新

putIfAbsent

V putIfAbsent(K key,V value)

如果指定的key相关联value不存在,则与给定值相关联,并返回新值,反之返回key关联的旧值。

map.putIfAbsent(3, "d");

新增

默认实现的类似转换

以下仅是方法的类似转换,区别是方法本身是原子实现,属于线程安全的,转换得到的例子则无法保证线程安全,存在并发问题。

compute

 V oldValue = map.get(key);
 V newValue = remappingFunction.apply(key, oldValue);
 if (oldValue != null ) {
    if (newValue != null)
       map.replace(key, oldValue, newValue);
    else
       map.remove(key, oldValue);
 } else {
    if (newValue != null)
       map.putIfAbsent(key, newValue);
    else
       return null;
 }

computeIfAbsent

 if (map.get(key) == null) {
     V newValue = mappingFunction.apply(key);
     if (newValue != null)
         return map.putIfAbsent(key, newValue);
 }

computeIfPresent

 if (map.get(key) != null) {
     V oldValue = map.get(key);
     V newValue = remappingFunction.apply(key, oldValue);
     if (newValue != null)
         map.replace(key, oldValue, newValue);
     else
         map.remove(key, oldValue);
 }

putIfAbsent

 if (!map.containsKey(key))
   return map.put(key, value);
 else
   return map.get(key);

参考

Interface ConcurrentMap<K,V>

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-11-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基础
  • 默认实现的类似转换
    • compute
      • computeIfAbsent
        • computeIfPresent
          • putIfAbsent
          • 参考
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档