HashMap.computeIfAbsent
如果需要向Map中push一个键值对,需要判断K key在当前map中是否已经存在,不存在则通过后面的 Function<? super K, ? extends V> mappingFunction 来进行value计算,且将结果当作value同key一起push到Map中。
computeIfAbsent() 方法的用法总结:
只有在当前 Map 中 key 对应的值不存在或为 null 时 ,才调用 mappingFunction,并在 mappingFunction 执行结果非 null 时,将结果跟 key 关联,mappingFunction 为空时 将抛出空指针异常。
公共代码:
Map <String, List<Integer>> map=new HashMap<>();
List<Integer> l1=new ArrayList();List <Integer> l2=new ArrayList<>();
l1.add(1);l1.add(11);l2.add(2);l2.add(22);
map.put("1",l1);
map.put("2",l2);
接下来就是使用了:
写法1:
List<Integer> l3=new ArrayList<>();l3.add(3);l3.add(33);
System.out.println(map.computeIfAbsent("2",v->l3));
System.out.println(map);
结果:如果原来map中有2,那么不会更新原来的值,并且computeIfAbsent方法返回原有的2这条值对于的value
[2, 22]
{1=[1, 11], 2=[2, 22]}
写法2:
List<Integer> l3=new ArrayList<>();l3.add(3);l3.add(33);
System.out.println(map.computeIfAbsent("3",v->l3));
System.out.println(map);
结果:如果原来map中无3那么会向map中新增3这条值,并且computeIfAbsent方法返回新增的3这条值的value
[3, 33]
{1=[1, 11], 2=[2, 22], 3=[3, 33]}
写法3:
System.out.pr