JDK1.8 HashMap中computeIfAbsent、computeIfPresent、compute方法的区别和例子
1)computeIfAbsent
1、它当键不存在时或者键存在但是值为null时,后面的Function类才会起到作用。
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
hashMap.put(3,null);
Integer in = hashMap.computeIfAbsent(3,(k)->10);
System.out.println(in);
System.out.println(hashMap.get(3));
注意:这里虽然key是存在的,但是由于值为null,还是会使用
Function函数的apply方法,运行结果如下:
还需要注意的是,如果key不存在,并且Function类实现的apply方法返回值不为null,就会将这个key作为新节点增加进去,value为apply返回值
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
hashMap.put(3,null);
System.out.println("执行computeIfAbsent方法之前:"+hashMap.get(new Integer(4)));
Integer in = hashMap.computeIfAbsent(4,(k)->20);
System.out.println("执行computeIfAbsent方法之后:"+hashMap.get(new Integer(4)));
结果如下图:
2)computeIfPresent
1、它只有当键存在的时候,后面BiFunction类才会起到作用,
会将BiFunction类的apply方法的返回值覆盖键的当前值,
但是如果返回值为null,就会进行节点的删除
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
hashMap.put(3,10);
System.out.println("执行computeIfAbsent方法之前:"+hashMap.get(new Integer(3)));
Integer in = hashMap.computeIfPresent(3,(k,v)->null);
System.out.println("执行computeIfAbsent方法之后:"+hashMap.get(new Integer(3)));
结果如下图:
3)compute
1、键存不存在后面的BiFunction类都会起到作用
2、但是相对的,会分两种情况进行删除或者新增节点
1)如果key存在,并且BiFunction的apply方法返回值
不为null,就会进行值的更新,否则就会进行节点删除
2)如果key不存在,并且BiFunction的apply方法返回值
不为null,就会进行节点的新增
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
hashMap.put(3,10);
//测试key存在,并且BiFunction的apply方法返回值为null的情况
System.out.println("使用compute之前:"+hashMap.get(new Integer(3)));
Integer in = hashMap.compute(3,(k,v)->300);
System.out.println("使用compute之后:"+hashMap.get(new Integer(3)));
//测试key存在,并且BiFunction的apply方法返回值为null的情况
System.out.println("使用compute之前:"+hashMap.get(new Integer(3)));
in = hashMap.compute(3,(k,v)->null);
System.out.println("使用compute之后:"+hashMap.get(new Integer(3)));
结果如下:
HashMap<Integer,Integer> hashMap = new HashMap<>(10,0.5f);
hashMap.put(3,10);
//测试key不存在
System.out.println("使用compute之前:"+hashMap.get(new Integer(5)));
Integer in = hashMap.compute(5,(k,v)->300);
System.out.println("使用compute之后:"+hashMap.get(new Integer(5)));
结果如下图:
有错误欢迎指出!!!