putIfAbsent
判断是否存在,不存在则设置
hashmap.putIfAbsent(K key, V value)
例子如下:
public static void main(String[] args) {//hashmap.putIfAbsent(K key, V value)HashMap hashMap = Maps.newHashMap();hashMap.put("aa","one");hashMap.putIfAbsent("bb","two");hashMap.values().stream().forEach(e->{System.out.println(e);});hashMap.putIfAbsent("bb","three");hashMap.values().stream().forEach(e->{System.out.println(e);});}
,输出如下:
computeIfAbsent
判断执行的key是否存在,存在则还回对应的value,如果key不存在,则设置进去。
hashmap.computeIfAbsent(K key, Function remappingFunction)
如下例子:
HashMap<String,Integer> hashMap = Maps.newHashMap();hashMap.put("one",280);hashMap.put("two",320);hashMap.put("three",410);Integer aa = hashMap.computeIfAbsent("one",key->290);System.out.println("aa=====:"+aa);System.out.println(hashMap);
输出如下:
computeIfPresent
对hashmap里面的key做判断,存在则对里面的value做重新计算,不存在则还回null
对hashmap里面指定的key的值做重新计算。
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
例子如下:
HashMap<String,Integer> hashMap = Maps.newHashMap();hashMap.put("one",280);hashMap.put("two",320);hashMap.put("three",410);Integer aa = hashMap.computeIfPresent("four",(key,value)->290);System.out.println("aa=====:"+aa);System.out.println(hashMap);
还回
存在则重新计算如下:还回的是计算过的值
HashMap<String,Integer> hashMap = Maps.newHashMap();hashMap.put("one",280);hashMap.put("two",320);hashMap.put("three",410);Integer aa = hashMap.computeIfPresent("one",(key,value)->290);System.out.println("aa=====:"+aa);System.out.println(hashMap);
结果如下: