编程中经常遇到这种数据结构,判断一个map中是否存在这个key,如果存在则处理value的数据,如果不存在,则创建一个满足value要求的数据结构放到value中。
简单解释一下:
map.computeIfAbsent(x,y) map中不存在key为x的值时,将y作为value,x作为key放入map中。
computeIfPresent(x,y)–> 1.返回与指定键关联的新值 2.如果没有与键关联的值,则返回null
代码示例:
public class J1 {
static Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("age", 12);
put("name", 10);
}
};
static Map<String, Map<String, Integer>> mapHashMap = Maps.newHashMap();
public static void main(String[] args) {
// map.computeIfAbsent("sex", key -> {return 5;});
mapHashMap.computeIfAbsent("sex", key -> Maps.newHashMap());
mapHashMap.computeIfPresent("sex", (key, value) -> {
value=map;
return value;
});
System.out.println(mapHashMap);
}
}
运行截图如下:
附源码:
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
put(key, newValue);
return newValue;
} else {
remove(key);
return null;
}
} else {
return null;
}
}
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}