1、 putIfAbsent
putIfAbsent() 方法会先判断指定的键(key)是否存在,不存在则将键/值对插入到 HashMap 中。
// putIfAbsent() 方法会先判断指定的键(key)是否存在,不存在则将键/值对插入到 HashMap 中。
Map<String, String> map = new HashMap<>();
map.putIfAbsent("1", "张三");
map.putIfAbsent("1", "李四");
System.out.println(map);
结果:
2、computeIfAbsent
computeIfAbsent() 方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中。
// computeIfAbsent() 方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中。
Map<String, String> map = new HashMap<>();
map.computeIfAbsent("1", key -> "张三");
map.computeIfAbsent("1", key -> "李四");
System.out.println(map);
结果:
可以发现putIfAbsent()和computeIfAbsent() 基本相同,都是检查map中key的value是否存在,不存在则插入。那他们有什么区别呢?
(1)、value为null时:
putIfAbsent()是没有对插入的value进行判断的,也就是说putIfAbsent()是可以插入null值的。而computeIfAbsent()会对value进行判空,若是为null,则不会插入:
// value为null可以插入
Map<String, String> map = new HashMap<>();
map.putIfAbsent("1", null);
System.out.println(map);
// value为null,插入不了
Map<String, String> map2 = new HashMap<>();
map2.computeIfAbsent("1", key -> null);
System.out.println(map2);
结果:
(2)、当value为list时:
computeIfAbsent()可以成功插入list并添加元素
Map<String, List<String>> map2 = new HashMap<>();
map2.computeIfAbsent("1", key -> new ArrayList<>()).add("张三");
结果:
putIfAbsent()会报空指针异常
Map<String, List<String>> map = new HashMap<>();
map.putIfAbsent("1", new ArrayList<>()).add("张三");
System.out.println(map);
结果:
3、computeIfPresent
computeIfPresent() 方法对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。
Map<String, String> map = new HashMap<>();
// 不存在时插入
map.computeIfAbsent("1", key -> "张三");
// 存在才插入
map.computeIfPresent("1", (k, v) -> "李四");
map.computeIfPresent("2", (k, v) -> "李四");
System.out.println(map);
结果:不存在的无法插入
当value时null时:
Map<String, String> map = new HashMap<>();
// 不存在时插入
map.computeIfAbsent("1", key -> "张三");
// 存在才插入
map.computeIfPresent("1", (k, v) -> null);
System.out.println(map);
结果:
4、forEach
遍历:
Map<String, String> map = new HashMap<>();
map.put("1", "张三");
map.put("2", "李四");
map.put("3", "王二麻子");
map.forEach((k, v) -> System.out.println(k + " " + v));
结果: