Map<String, Double> map = new HashMap();
map.computeIfAbsent(“list”,(key)->0d);
解读:map中如果不存在key为list的值,或者key为list对应的值为null,就会把0d赋值给key为list的,并且会返回赋予的值,这里为0d;
2.
if存在便计算
String ret;
Map<String, String> map1 = new HashMap<>();
ret = map1.computeIfPresent("a", (key, value) -> key + value); //ret null, map 为 {}
map1.put("a", "a对应的值"); //map 为 ["a":null]
ret = map1.computeIfPresent("a", (key, value) -> value); //ret null, map 为 {"a":null}
本文深入解析了Java中Map的computeIfPresent和computeIfAbsent方法的使用场景与实现原理。通过具体代码示例,展示了如何在Map中进行条件计算和赋值操作,适用于Java开发者学习和理解Map的高级功能。
979

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



