Map接口computeIfAbsent()方法和computeIfPresent()方法

computeIfAbsent()方法

computeIfAbsent() 方法对 Map中指定 key 的值进行重新计算,如果不存在这个 key,或者该key对应的value为null,则把新值添加到 Map 中。

show me your code,don't bibi;

举例:

  • eg1
        Map<String,String> map = new HashMap<>();
        map.put("abc","dad");
        String abc = map.computeIfAbsent("abc", key -> "VVV");
        System.out.println(abc);
        System.out.println(map);

因为该key之前有key "abc",所以不会放入新值
结果打印:

dad
{abc=dad}
  • eg2
        Map<String,String> map = new HashMap<>();
        map.put("abc",null);
        String abc = map.computeIfAbsent("abc", key -> "VVV");
        System.out.println(abc);
        System.out.println(map);

因为“abc”对应的value为null,computeIfAbsent会把新值放入。

VVV
{abc=VVV}
  • eg3
        Map<String,String> map = new HashMap<>();
        map.put("abcd",null);
        String abc = map.computeIfAbsent("abc", key -> "VVV");
        System.out.println(abc);
        System.out.println(map);

因为该key之前没有key "abc",所以会放入新值

VVV
{abc=VVV, abcd=null}
  • eg4
        Map<String,String> map = new HashMap<>();
        map.put("abcdd","qqq");
        String abc = map.computeIfAbsent("abc", key -> null);
        System.out.println(abc);
        System.out.println(map);

因为key -> null,map不放入新值

null
{abcdd=qqq}

computeIfPresent()方法

computeIfPresent() 方法对 Map中指定 key 的值进行重新计算,前提是该 key 存在于 Map中。


  • eg1
        Map<String,String> map = new HashMap<>();
        map.put("abc", "VVV");
        String abc = map.computeIfPresent("abc", (key, value) -> null);
        System.out.println(abc);
        System.out.println(map);
null
{}
  • eg2
        Map<String,Integer> map = new HashMap<>();
        map.put("abc", 10);
        Integer abc = map.computeIfPresent("abc", (key, value) -> value + 1);
        System.out.println(abc);
        System.out.println(map);
11
{abc=11}

JAVA8 ConcurrentHashMap.computeIfAbsent 的使用及说明

ConcurrentHashMap.computeIfAbsent()方法保证了线程安全

对于以前写的代码

        Map<String,Object> map = new ConcurrentHashMap<>();
        Object v = map.get("key");
        if (v == null){
            synchronized (Test01.class){
                v = map.get("key");
                if (v == null){
                    v = new Object();
                    map.put("key", v);
                }
            }
        }

        System.out.println(map);

可简化为:

        Map<String,Object> map = new ConcurrentHashMap<>();

        map.computeIfAbsent("key", value-> new Object());
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容