1. computeIfAbsent
没有key,就新增key,将计算结果作为value存入map,并返回计算结果
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.computeIfAbsent("b", key -> {
String str = "hello";
return "222";
});
System.out.println("result: " + result); // result: 222
System.out.println(map); // {a=111, b=222}
有key,返回map中key对应的value
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.computeIfAbsent("a", key -> {
return "222";
});
System.out.println("result: " + result); // result: 111
System.out.println(map); // {a=111}
2. computeIfPresent
有key,计算结果,存入map,并返回计算结果
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.computeIfPresent("a", (k, v) -> "222");
System.out.println("result: " + result); // result: 222
System.out.println(map); // {a=222}
没有key,返回null
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.computeIfPresent("b", (k, v) -> "222");
System.out.println("result: " + result); // result: null
System.out.println(map); // {a=111}
3. compute
有key,计算结果存入map,并返回计算结果
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.compute("a", (k, v) -> "222");
System.out.println("result: " + result); // result: 222
System.out.println(map); // {a=222}
没有key,就新增key,将计算结果作为value存入map,并返回计算结果
HashMap<String, String> map = new HashMap();
map.put("a", "111");
String result = map.compute("b", (k, v) -> "222");
System.out.println("result: " + result); // result: 222
System.out.println(map); // {a=111, b=222}