HashMap中的computeIfAbsent方法如何使用

2026-02-12 06:24:26

1、1.新建一个类:TestHashMap.java

HashMap中的computeIfAbsent方法如何使用

2、2.声明main方法

HashMap中的computeIfAbsent方法如何使用

3、3.创建一个HashMap对象

HashMap中的computeIfAbsent方法如何使用

4、4.执行HashMap的putIfAbsent方法

HashMap中的computeIfAbsent方法如何使用

5、5.分别获取和打印key为a和b的值

HashMap中的computeIfAbsent方法如何使用

6、6.根据打印结果可以发现,key为a的值没有被覆盖,key为b的值被覆盖了

HashMap中的computeIfAbsent方法如何使用

7、7.根据以上可以总结:HashMap的putIfAbsent方法的功能是,当map集合中不存在某个键或者该键对应的值为NULL时,将值设置进map集合

猜你喜欢