Map中的compute、computeIfAbsent和computeIfPresent的使用和区别

Map中的compute、computeIfAbsent和computeIfPresent的使用和区别

    • computeIfAbsent
    • computeIfPresent
    • compute
    • 完整代码

先准备一个简单的map数据吧

        Map<Long, String> testMap = new HashMap<>();
        testMap.put(1L, "张三");
        testMap.put(2L, "李四");
        testMap.put(3L, "王五");

computeIfAbsent

简单来说这个方法就是根据第一个参数key,去查询map,只有当返回值为null即Map中查询不到对应的数据时,向Map中添加一条数据

        //测试,没有新增
        testMap.computeIfAbsent(4L, aLong -> "computeIfAbsent");
        //有返回值,不做任何操作
        testMap.computeIfAbsent(3L, aLong -> "computeIfAbsent2");

操作之前的截图
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第1张图片
没有的新增
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第2张图片
有的不做操作
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第3张图片

computeIfPresent

简单来说这个方法就是根据第一个参数key,去查询map,如果查询到了就更新对应的值,如果查询不到,不做任何操作

        //Map中有就更新,没有不做操作
        testMap.computeIfPresent(2L, (aLong, s) -> "computeIfPresent");
        //Map中没有不做操作
        testMap.computeIfPresent(5L, (aLong, s) -> "computeIfPresent2");

有就更新
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第4张图片

没有不做操作
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第5张图片

compute

简单来说这个方法就是根据第一个参数key,去查询map,无论是否查询到,都会执行第二个方法体,没有就新增,有就更新值

        testMap.compute(1L, (aLong, s) -> "compute");
        testMap.compute(6L, (aLong, s) -> "compute2");

有就更新
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第6张图片

没有就新增
Map中的compute、computeIfAbsent和computeIfPresent的使用和区别_第7张图片

完整代码

Map<Long, String> testMap = new HashMap<>();
testMap.put(1L, "张三");
testMap.put(2L, "李四");
testMap.put(3L, "王五");
//测试,没有新增
testMap.computeIfAbsent(4L, aLong -> "computeIfAbsent");
//有返回值,不做任何操作
testMap.computeIfAbsent(3L, aLong -> "computeIfAbsent2");
//Map中有就更新,没有不做操作
testMap.computeIfPresent(2L, (aLong, s) -> "computeIfPresent");
//Map中没有不做操作
testMap.computeIfPresent(5L, (aLong, s) -> "computeIfPresent2");
//有就更新
testMap.compute(1L, (aLong, s) -> "compute");
//没有就新增
testMap.compute(6L, (aLong, s) -> "compute2");

你可能感兴趣的:(Java基础,java,开发语言)