菜鸟教程 -- 学的不仅是技术,更是梦想!

Java 教程
(追記) (追記ここまで)

Java HashMap computeIfAbsent() 方法

Java HashMap Java HashMap

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

computeIfAbsent() 方法的语法为:

hashmap.computeIfAbsent(K key, Function remappingFunction)

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

参数说明:

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

返回值

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

实例

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

实例

import java.util.HashMap;

class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();

// 往HashMap中添加映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);

// 计算 Shirt 的值
int shirtPrice = 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: 280
Updated 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 已经存在的情况:

实例

import java.util.HashMap;

class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();

// 往HashMap中添加映射关系
prices.put("Shoes", 180);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);

// Shoes中的映射关系已经存在
// Shoes并没有计算新值
int shoePrice = 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: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}

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

Java HashMap Java HashMap

AI 思考中...

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /