java 8 中的computeIfAbsent方法简介

本文介绍了Java 8中的Map.computeIfAbsent方法,详细阐述了当Key关联的值非空、使用Mapping function计算值、Mapping Function返回null以及抛出异常四种情况下的行为。该方法在Map中提供了优雅的条件计算和存储功能。

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


title: java 8 中的computeIfAbsent方法简介
date: 2020-10-21 19:38:26
tags:


java 8 中的computeIfAbsent方法简介

1) Map.computeIfAbsent 方法

先看函数签名

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

这个computeIfAbsent 方法需要两个参数,第一个参数是key,第二个参数是mappingFunction,只有在mapping不存在时才调用 mapping function。

1.1)和一个non-null 值关联的Key

首先,检查key是否在map中存在。如果key存在,且对应non-null 值。然后他返回一个值。

Map<String, Integer> stringLength = new HashMap<>();
stringLength.put("John", 5);
assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 5);

验证以上代码,键“ John”具有非空映射,它返回值5。如果使用了映射函数,则该函数返回4的长度。

1.2) 使用Mapping function 计算value

此外,如果key不存在于mapping中,或者与键相关的是null值,则它将尝试使用给定的mappingFunction计算值。 另外,除非计算value为空,否则它将计算的值输入到mapping中。

computeIfAbsent方法中mappingFunction的用法:

Map<String, Integer> stringLength = new HashMap<>();
assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 4);
assertEquals((long)stringLength.get("John"), 4);

由于key“ John”不存在,因此它通过将key作为参数传递给mappingFunction来计算值。

1.3)Mapping Function 返回null

如果MappingFunction 返回null,map里面不会存入。

Map<String, Integer> stringLength = new HashMap<>();
assertEquals(stringLength.computeIfAbsent("John", s -> null), null);
assertNull(stringLength.get("John"));

1.4) Mapping Function 抛异常

如果 mappingFunction 函数抛了异常,那么异常会被computeIfAbsent 再次抛出。map不会存入。

@Test(expected = RuntimeException.class)
public void whenMappingFunctionThrowsException_thenExceptionIsRethrown() {
    Map<String, Integer> stringLength = new HashMap<>();
    stringLength.computeIfAbsent("John", s -> { throw new RuntimeException(); });
}

mappingFunction抛出RuntimeException,该RuntimeException传播回了computeIfAbsent方法。

2) 结论

函数签名和用法,已经处理不同场景下的case。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值