HashMap.computeIfAbsent与computeIfPresent

本文详细介绍了HashMap的computeIfAbsent和computeIfPresent方法的使用,包括7种不同写法的示例及执行结果。computeIfAbsent在键对应的值不存在或为null时,使用提供的函数计算新值并插入;computeIfPresent则在键存在时,使用双参数函数重新计算键的值,可能更新或删除原有值。

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

HashMap.computeIfAbsent
如果需要向Map中push一个键值对,需要判断K key在当前map中是否已经存在,不存在则通过后面的 Function<? super K, ? extends V> mappingFunction 来进行value计算,且将结果当作value同key一起push到Map中。

computeIfAbsent() 方法的用法总结:

只有在当前 Map 中 key 对应的值不存在或为 null 时 ,才调用 mappingFunction,并在 mappingFunction 执行结果非 null 时,将结果跟 key 关联,mappingFunction 为空时 将抛出空指针异常。

公共代码:

Map <String, List<Integer>> map=new HashMap<>();
List<Integer> l1=new ArrayList();List <Integer> l2=new ArrayList<>();
l1.add(1);l1.add(11);l2.add(2);l2.add(22);
map.put("1",l1);
map.put("2",l2);

接下来就是使用了:

写法1:

List<Integer> l3=new ArrayList<>();l3.add(3);l3.add(33);
System.out.println(map.computeIfAbsent("2",v->l3));
System.out.println(map);

结果:如果原来map中有2,那么不会更新原来的值,并且computeIfAbsent方法返回原有的2这条值对于的value

[2, 22]
{1=[1, 11], 2=[2, 22]}

写法2:

List<Integer> l3=new ArrayList<>();l3.add(3);l3.add(33);
System.out.println(map.computeIfAbsent("3",v->l3));
System.out.println(map);

结果:如果原来map中无3那么会向map中新增3这条值,并且computeIfAbsent方法返回新增的3这条值的value

[3, 33]
{1=[1, 11], 2=[2, 22], 3=[3, 33]}

写法3:

System.out.pr
### Java Map `computeIfAbsent` `computeIfPresent` 方法区别及用法 #### 方法定义功能差异 `computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)` 方法用于当指定键对应的值不存在时计算其值并将其映射到该键上。如果键已经存在,则不会调用给定函数,并返回现有值。 ```java Map<String, Integer> map = new HashMap<>(); Integer result1 = map.computeIfAbsent("key", k -> { System.out.println("Computing for absent"); return 1; }); System.out.println(result1); // 输出: Computing for absent\n1 ``` 此不同的是,`computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)` 只有在键已存在于映射中时才会更新它的值;否则不执行任何操作并返回null[^1]。 ```java map.put("existingKey", 2); Integer result2 = map.computeIfPresent("existingKey", (k, v) -> { System.out.println("Updating existing entry."); return v + 1; }); System.out.println(result2); // 输出: Updating existing entry.\n3 ``` #### 参数说明 两个方法都接受一个参数作为键来查找条目。对于 `computeIfAbsent`, 需要提供一个 `Function` 接口实例用来生成新值; 对于 `computeIfPresent`, 则需传入一个 `BiFunction` 实现类以便基于当前值创建新的关联值[^2]。 #### 使用场景举例 假设有一个缓存系统存储网页内容摘要,在处理请求之前先尝试从内存中的哈希表获取数据: - 如果找不到对应记录 (`computeIfAbsent`) ,则发起HTTP GET 请求下载页面HTML 并解析提取摘要信息保存至缓存; - 若命中缓存(`computeIfPresent`) , 更新访问时间戳以防止过期淘汰机制误删常用资源。 通过这种方式可以有效地减少重复劳动提高效率的同时保持良好的用户体验[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值