上班摸鱼的偶然一次机会,看到了一篇关于Java8对map的新增的方法,顿觉学术甚浅,遂写了个demo进行学习。
computeIfAbsent:
* If the specified key is not already associated with a value (or is mapped
* to {@code null}), attempts to compute its value using the given mapping
* function and enters it into this map unless {@code 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;
}
方法有两个参数:一个是key,另一个是个函数式接口Function,这就是上面所说的 映射函数。
首先判断通过该key是否是绑定了元素,即get(key)是否为空,当为空时则通过该函数式接口,调用Function.apply()方法,得到新值赋值
给newValue,当newValue不为空,则放入map里并返回newValue;当不为空时则将当前key对应的value返回。
即: 该方法 (computeIfAbsent) 的返回值是该key对应的value。
//
public class MapIfAbsent {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(16);
String a=map.get("a");
if (a==null){
a="a没有值,重新手动赋值";
}
System.out.println("-------------------------");
map.forEach((k,v)-> System.out.println(k+":"+v));
System.out.println();
System.out.println();
String b=map.computeIfAbsent("b",e->"b没有值,手动赋值一下");
System.out.println("=========================");
map.forEach((k,v)-> System.out.println(k+":"+v));
System.out.println("a:"+a);
System.out.println("b:"+b);
}
}
打印结果为:
可以看出:
1、第一次遍历map是没有值的;
2、调用了computeIfAbsent()方法,返回值b是“b”对应的value,且map也新增了这条k-v数据,第二次遍历有数据的;
那问题来了,当该key对应的value有值时,调用方法会返回什么呢?
public class MapIfAbsent {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(16);
String b=map.computeIfAbsent("b",e->"b没有值,手动赋值一下");
System.out.println("------------------------");
map.forEach((k,v)-> System.out.println(k+":"+v));
String newB = map.computeIfAbsent("b", e -> "给b赋个新值呢");
System.out.println("=========================");
map.forEach((k,v)-> System.out.println(k+":"+v));
System.out.println();
System.out.println();
System.out.println();
System.out.println("b:"+b);
System.out.println("b:"+newB);
}
}
给key为“b”的元素赋新值 ==“给b赋个新值呢”,==map会输出什么呢?
map的元素的value并没有发生改变,方法的返回值就是原来key对应的value。
由此可见,computeIfAbsent()方法顾名思义,“当不存在时计算”,当当前key没有对应元素时则通过函数式接口新增value,将改键值对保存到map里,同时返回value;当有对应的value则返回value,且函数式接口赋的新值并不会改变原先的value。
努力搬砖,为了不再被人看不起!😃😃😃