computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
如果map里面不存在key,则执行mappingFunction
computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
如果map里面存在key,则执行remappingFunction
compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
无论map里面是不是有key,都执行remappingFunction
注意computeIfAbsent的第二个参数是k,computeIfPresent和compute第二个参数都是(k,v)
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap();
// key不存在的时候,执行后面的方法
List<String> list1 = map.computeIfAbsent("list1", k -> new ArrayList<>());
list1.add("addList1");
map.put("absentExist", new ArrayList<>());
List<String> absentExist = map.computeIfAbsent("absentExist", k -> new ArrayList<>());
absentExist.add("aaaaaa the key is exist

本文详细介绍了JDK 8中Map接口的computeIfAbsent、computeIfPresent和compute方法,重点讨论了它们在处理键值对时的行为,特别是参数k和(k, v)的使用场景。"
107684901,9804832,C++基础教程:数学运算、随机数、数组与字符串解析,"['C++', '数学库', '随机数生成', '数组操作', '字符串处理', '结构体']
最低0.47元/天 解锁文章
2677

被折叠的 条评论
为什么被折叠?



