java8 Map 的compute的用法
介绍
compute是java8 Map接口带来的默认接口函数, 其他相关函数computeIfPresent computeIfAbsent
compute
源码如下, 1. newValue替换oldValue,返回newValue
2. 如果newValue==null则剔除元素。
//源码
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
remove(key);
return null;
} else {
// nothing to do. Leave things as they were.
return null;
}
} else {
// add or replace old mapping
put(key, newValue);
return newValue;
}
}
示例一、统计数组中每个数的出现次数
Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 1, 1, 2, 3};
Arrays.asList(arr).forEach(element -> {
map.compute(element, (k, v) -> {
if (v == null) {
return 1;
} else {
return v + 1;
}
});
});
示例二、删除某个元素
Arrays.asList(arr).forEach(element -> {
map.compute(element, (k, v) -> {
return null;
});
});
computeIfAbsent
源码如下。1. value!=null直接返回,value==null通过mappingFunction得到新值返回
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;
}
示例一、map给未赋值的key赋值
Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 2, 3};
map.put(1, 1);
Arrays.asList(arr).forEach(key -> {
map.computeIfAbsent(key, k -> {
return k;
});
});
computeIfPresent
源码如下。1. value!=null根据remappingFunction得到新值,value==null则返回null
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;
}
}
示例一、map给已存在的key value + 1
Map<Integer, Integer> map = Maps.newHashMap();
Integer[] arr = new Integer[]{1, 2, 3};
map.put(1, 1);
Arrays.asList(arr).forEach(key -> {
map.computeIfPresent(key, (k, v) -> {
return v + 1;
});
});