Map中的compute、computeIfPresent和computeIfAbsent的使用和区别
Map中的compute、computeIfPresent和computeIfAbsent的使用和区别
Map map = new HashMap();
map.put(1, "one");
map.put(2, "two");
Set set = map.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
System.out.println("===================================");
/**
* Map中的compute、computeIfAbsent和computeIfPresent的使用和区别
* computeIfAbsent
* V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
* 根据参数key去查找map,如果返回的值为null,则执行第二个参数(Function)的方法体,在方法体中的返回值作为最终方法的返回值V,并且同时设置到map中。
*/
map.computeIfAbsent(3, k -> k + "-three");//第二个参数中lambda的 k 就是,第一个参数key
set = map.entrySet();
iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
System.out.println("===================================");
/**
* computeIfPresent
* V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
* 根据key查找值,如果查找到参数,则执行第二个参数(function)方法体进行数据处理,以方法体的返回值作为最终的返回值V,并且同时更新Map中对应key的value值。
* 如果查找的value为空,则不会进入方法体。
*/
//map.computeIfPresent(1, (k, v) -> null);
map.computeIfPresent(2, (k, v) -> k + "-" + v);
map.computeIfPresent(9, (k, v) -> {
System.out.println("computeIfPresent() is start");
return k + "-" + v;
});
set = map.entrySet();
iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
System.out.println("===================================");
/**
* compute
* V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
* 根据key查找值,如果查找到参数,则执行第二个参数(function)方法体进行数据处理,以方法体的返回值作为最终的返回值V,并且同时更新Map中对应key的value值。
* 如果查找的value为空,依然进入方法体。
*/
//map.compute(1, (k, v) -> null);
map.compute(1, (k, v) -> k + "-" + v);
map.compute(9, (k, v) -> {
System.out.println("compute() is start");
return k + "-" + v;
});
set = map.entrySet();
iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
/* 运行结果如下:
1=one
2=two
===================================
1=one
2=two
3=3-three
===================================
1=one
2=2-two
3=3-three
===================================
compute() is start
1=1-one
2=2-two
3=3-three
9=9-null
*/
总结:
computeIfAbsent比较好理解,如果根据key能查到就OK ,查不到就通过第二个lambda参数给它返回一个值
compute和computeIfPresent的区别如下:
computeIfPresent 如果value为null,不执行第二个参数方法体。
compute 如果value为null,也会执行第二个参数方法体。
注意:如果这两个方法第二个参数方法体返回null,则会在map中删除原有记录。

浙公网安备 33010602011771号