computeIfAbsent 和 putIfAbsent 区别有以下三点:
- 当key 存在的时候,如果value获取比较昂贵的话,putifAbsent 就白白浪费时间在获取这个昂贵的value上。
- key 不存在的时候,putIfAbsent 返回null, 小心空指针,而computeIfAbsent 返回计算后的值。
- 当key 不存在的时候,putifAbsent 允许put null 进去,而 computeIfAbsent 不能,之后进行containsKey查询是有区别的。
具体用法如下:
- putIfAbsent
- 传统的put方法,只要key存在,value值就会被覆盖,注意 put方法返回的是put之前的值,如果无put之前的值返回nul
- putIfAbsent方法,只有在key不存在或者key为null的时候,value值才会被覆盖
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
使用场景:如果我们要变更某个key的值,我们又不知道key是否存在的情况下,而又不希望增加key的情况使用。
- computeIfAbsent
在返回值上不一样,vaue值不存在的时候,返回的是新的value值,同时可以通过自定义一些条件进行过滤。
value 存在的时候返回的是旧值。
public class MapTest3 {
static List<People> peopleList = Arrays.asList(
new People("张三",2),
new People("李四",15),
new People("tom",8),
new People("jack",10),
new People("lili",8),
new People("lucy",2));
public static void main(String[] args) {
testComputeIfAbsent();
}
private static void testComputeIfAbsent(){
//声明接收结果的 map
Map<Integer, List<People>> resultMap = new HashMap<Integer, List<People>>();
//按照年龄分组
for (People people : peopleList) {
//putIfAbsent方法,只有在key不存在或者key为null的时候,value值才会被覆盖
// 返回的旧值,如果key不存在则返回null
List<People> s = resultMap.putIfAbsent(people.getAge(), new ArrayList<People>());
if(s==null) {//此时重新获取一次,就能到初始化好的List数组
s = resultMap.putIfAbsent(people.getAge(), new ArrayList<People>());
}
s.add(people);
}
System.out.println(resultMap);
resultMap = new HashMap<Integer, List<People>>();
//对5岁以上的人进行分组
for (People people : peopleList) {
//如果value值不存在,返回的是新的value值
//如果value存在,则返回的是旧值
List<People> s = resultMap.computeIfAbsent(people.getAge(), k ->{
if(k>5) {
return new ArrayList<People>();
}
return null;
});
if(s!=null) {
s.add(people);
}
}
System.out.println(resultMap);
}
}