Java HashMap computeIfAbsent() 方法

computeIfAbsent() 方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中。

computeIfAbsent() 方法的语法为:

hashmap.computeIfAbsent(K key, Function remappingFunction)

注:hashmap 是 HashMap 类的一个对象。

参数说明:

key - 键

remappingFunction - 重新映射函数,用于重新计算值

返回值

如果 key 对应的 value 不存在,则使用获取 remappingFunction 重新计算后的值,并保存为该 key 的 value,否则返回 value。

实例

以下实例演示了 computeIfAbsent() 方法的使用:

实例

importjava.util.HashMap;

classMain{

publicstaticvoidmain(String[]args){

// 创建一个 HashMap

HashMap<String, Integer>prices=newHashMap<>();

// 往HashMap中添加映射项

prices.put("Shoes",200);

prices.put("Bag",300);

prices.put("Pant",150);

System.out.println("HashMap: "+prices);

// 计算 Shirt 的值

intshirtPrice=prices.computeIfAbsent("Shirt", key->280);

System.out.println("Price of Shirt: "+shirtPrice);

// 输出更新后的HashMap

System.out.println("Updated HashMap: "+prices);

}

}

执行以上程序输出结果为:

HashMap: {Pant=150, Bag=300, Shoes=200}Price of Shirt: 280Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}

在以上实例中,我们创建了一个名为 prices 的 HashMap。

注意表达式:

prices.computeIfAbsent("Shirt", key -> 280)

代码中,我们使用了匿名函数  lambda 表达式key-> 280作为重新映射函数,prices.computeIfAbsent() 将 lambda 表达式返回的新值关联到 Shirt。

因为 Shirt 在 HashMap 中不存在,所以是新增了 key/value 对。

要了解有关 lambda 表达式的更多信息,请访问Java Lambda 表达式

当 key 已经存在的情况:

实例

importjava.util.HashMap;

classMain{

publicstaticvoidmain(String[]args){

// 创建一个 HashMap

HashMap<String, Integer>prices=newHashMap<>();

// 往HashMap中添加映射关系

prices.put("Shoes",180);

prices.put("Bag",300);

prices.put("Pant",150);

System.out.println("HashMap: "+prices);

// Shoes中的映射关系已经存在

// Shoes并没有计算新值

intshoePrice=prices.computeIfAbsent("Shoes",(key)->280);

System.out.println("Price of Shoes: "+shoePrice);

// 输出更新后的 HashMap

System.out.println("Updated HashMap: "+prices);

}

}

执行以上程序输出结果为:

HashMap: {Pant=150, Bag=300, Shoes=180}Price of Shoes: 180Updated HashMap: {Pant=150, Bag=300, Shoes=180}

在以上实例中, Shoes 的映射关系在 HashMap 中已经存在,所以不会为 Shoes 计算新值。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容