title: java 8 中的computeIfAbsent方法简介 date: 2020-10-21 19:38:26 tags:
先看函数签名
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)这个computeIfAbsent 方法需要两个参数,第一个参数是key,第二个参数是mappingFunction,只有在mapping不存在时才调用 mapping function。
首先,检查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的长度。
此外,如果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来计算值。
如果MappingFunction 返回null,map里面不会存入。
Map<String, Integer> stringLength = new HashMap<>(); assertEquals(stringLength.computeIfAbsent("John", s -> null), null); assertNull(stringLength.get("John"));如果 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方法。
函数签名和用法,已经处理不同场景下的case。