jdk1.8中map新特性compute,computeIfAbsent,computeIfPresent,putIfAbsent方法
1.compute
compute:key不存在添加,存在则对value进行操作
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
Integer integer = map.compute("4", (k, v) -> v+1);
Integer integer1 = map.compute("5", (k, v) -> {
if (v == null) {
return 0;
}
return v+1;
});
System.out.println(integer); //输出 5
System.out.println(integer1); //输出 0
System.out.println(map.toString()); //输出 {1=1, 2=2, 3=3, 4=5, 5=0}
2.computeIfAbsent
computeIfAbsent:当key存在返回当前value值,不存在则添加
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
Integer integer = map.computeIfAbsent("4", k -> 5);
//key不存在就添加
Integer integer1 = map.computeIfAbsent("5", k -> {
if (k.equals("5")){
return 50;
}
return 0;
});
System.out.println(integer); //输出 4
System.out.println(integer1); //输出 50
System.out.println(map.toString()); //输出 {1=1, 2=2, 3=3, 4=4, 5=50}
3.computeIfPresent
computeIfPresent :对在map中已有key的value进行操作。
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
//对集合中存在的key进行操作
Integer integer = map.computeIfPresent("4", (k, v) -> v+1);
Integer integer1 = map.computeIfPresent("5", (k, v) -> {
if (v == null) {
return 0;
}
return v+1;
});
System.out.println(integer); //输出 5
System.out.println(integer1); //输出 null
System.out.println(map.toString()); //输出 {1=1, 2=2, 3=3, 4=5}
4.putIfAbsent
putIfAbsent:map集合中key不存在 或 value为空时添加,如果key已经存在,则不进行操作,返回value。
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
map.put("5", null);
Integer integer = map.putIfAbsent("4", 5);
Integer integer1 = map.putIfAbsent("5", 0);
//等价于
/*if(!map.containsKey("5") || map.get("5") == null) {
map.put("5", 0);
}*/
System.out.println(integer); //输出 4
System.out.println(integer1); //输出 0
System.out.println(map.toString()); //输出 {1=1, 2=2, 3=3, 4=4, 5=0}