本文看下computeIfAbsent,用于实现当map中存在指定的key时则直接返回已存在的value,否则调用给定的java.util.function.Function
实现类获取一个初始的value,并put,最后返回。
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("zhangSan");
set.add("liSi");
hashMap.put("china", set);
// 判断map中是否存在,如果存在则添加元素到set中,如果不存在则新建set添加到hashMap中
if (hashMap.containsKey("china")) {
System.out.println("china 存在");
} else {
Set<String> setTmp = new HashSet<>();
setTmp.add("zhangSan");
setTmp.add("liSi");
hashMap.put("china", setTmp);
}
if (hashMap.containsKey("america")) {
} else {
System.out.println("america 不存在");
Set<String> setTmp = new HashSet<>();
setTmp.add("curry");
setTmp.add("kobe");
hashMap.put("america", setTmp);
}
System.out.println(hashMap.toString());
}
运行:
china 存在
america 不存在
{china=[liSi, zhangSan], america=[kobe, curry]}
Process finished with exit code 0
@Test
public void testComputeIfAbsent() {
Set<String> set = new HashSet<>();
set.add("zhangSan");
set.add("liSi");
hashMap.put("china", set);
hashMap.computeIfAbsent("china", s -> new HashSet() {
{
add("zhangSan");
add("liSi");
}
});
hashMap.computeIfAbsent("america", s -> new HashSet() {
{
System.out.println("america不存在");
add("curry");
add("kobe");
}
});
System.out.println(hashMap.toString());
}
运行:
america不存在
{china=[liSi, zhangSan], america=[kobe, curry]}
Process finished with exit code 0
以java.util.Map提供的default实现为例,具体的实现类如java.util.HashMap重写版本更加复杂,但核
不变,即行为不变(符合里氏替换原则)
,但default实现最简单,所以看下此,如下:
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
// key不存在
if ((v = get(key)) == null) {
V newValue;
// 调用传入的mappingFuncion获取value
if ((newValue = mappingFunction.apply(key)) != null) {
// put newValue
put(key, newValue);
// 返回new value,即mappingFunction apply后的结果
return newValue;
}
}
// key存在,则直接返回对应的v
return v;
}
computeIfAbsent() 的使用 。