default V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)app
指定的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}
V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)code
第一個是所選map的key,第二個是須要作的操做。這個方法當key值不存在時才起做用。當key存在返回當前value值,不存在執行函數並保存到map中.rem
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}
default V computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)io
對指定的在map中已經存在的key的value進行操做。只對已經存在key的進行操做,其餘不操做map
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}