2019独角兽企业重金招聘Python工程师标准>>>
compute(计算)
default V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
指定的key值在map中的value值进行操作, 如果key存在,则可操作value值; 如果key不存在,操作完成后key,value都保存到map中
Map<String,Integer> map= Maps.newHashMap();
map.put("1",1);
map.put("2",2);
map.put("3",3);
Integer integer = map.compute("3", (k,v) -> v+1 );
System.out.println(map);
Integer integer1 = map.compute("4", (k,v) -> v=9);
System.out.println(map);
输出:
{1=1, 2=2, 3=4}
{1=1, 2=2, 3=4, 4=9}
computeIfAbsent(不存在时计算)
V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)
第一个是所选map的key,第二个是需要做的操作。这个方法当key值不存在时才起作用。当key存在返回当前value值,不存在执行函数并保存到map中.
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
//key值存在,则不做操作
map.computeIfAbsent("1", key -> 90);
System.out.println(map);
//key 值不存在,则做操作
map.computeIfAbsent("4", key -> 90);
System.out.println(map);
输出:
{1=1, 2=2, 3=3}
{1=1, 2=2, 3=3, 4=90}
computeIfPresent(存在时计算)
default V computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)
对指定的在map中已经存在的key的value进行操作。只对已经存在key的进行操作,其他不操作
Map<String, Integer> map = Maps.newHashMap();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
//key值存在则计算
map.computeIfPresent("3", (key, value) -> value = 10);
System.out.println(map);
//key值不存在,则不做操作
map.computeIfPresent("4", (key, value) -> 90);
System.out.println(map);
输出:
{1=1, 2=2, 3=10}
{1=1, 2=2, 3=10}