ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Map#computeIfAbsent

2026/9/12 12:24:43 拓冰建站 浏览量
Map#computeIfAbsent

Map#computeIfAbsent

    • 1. 源码解析
      • 1.1 java.util.Map#computeIfAbsent
      • 2.demo

1. 源码解析

1.1 java.util.Map#computeIfAbsent

default V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction) {Objects.requireNonNull(mappingFunction);V v;if ((v = get(key)) == null) {// 如果map中的值为空,那么就回调lambda表达式生成值,参数为keyV newValue;if ((newValue = mappingFunction.apply(key)) != null) {// 将lambda中获取的值放入到map中put(key, newValue);// 返回的是lambda生成的值return newValue;}}//如果map中的值不为空,那么返回的是map中的值return v;}
  1. 如果map中的值为空,那么就回调lambda表达式生成值,参数为key
  2. 将lambda中获取的值放入到map中
  3. 返回的是lambda生成的值
  4. 如果map中的值不为空,那么返回的是map中的值
  5. mappingFunction为function,一个参数,一个返回值。
@FunctionalInterface
public interface Function<T, R> {R apply(T t);}

2.demo

public class mapTest {public static void main(String[] args) {Map<String, List<String>> map = new HashMap<>();List<String> valueList = map.computeIfAbsent("a", k -> new ArrayList<String>());valueList.add("value1");List<String> valueList2 = map.computeIfAbsent("a", k -> new ArrayList<String>());valueList2.add("value2");System.out.println(map);}
}

测试结果
在这里插入图片描述