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

本文详细介绍了Java中Map接口的computeIfAbsent、computeIfPresent和compute方法的使用,通过实例展示了它们如何根据键查询并更新或添加Map中的数据。这三个方法在Map操作中提供了便捷的条件赋值和更新功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

先准备一个简单的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");

操作之前的截图
在这里插入图片描述
没有的新增
在这里插入图片描述
有的不做操作
在这里插入图片描述

computeIfPresent

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

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

有就更新
在这里插入图片描述

没有不做操作
在这里插入图片描述

compute

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

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

有就更新
在这里插入图片描述

没有就新增
在这里插入图片描述

完整代码

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");
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值