跳到主要内容

Java HashMap computeIfAbsent() 方法

computeIfAbsent() 方法的语法是:

hashmap.computeIfAbsent(K key, Function remappingFunction)

这里,hashmapHashMap 类的一个对象。

computeIfAbsent() 方法的参数

computeIfAbsent() 方法接受 2 个参数:

  • key - 要与计算得到的值关联的键
  • remappingFunction - 为指定的 key 计算新值的函数

注意remapping function 不能接受两个参数。

computeIfAbsent() 方法的返回值

  • 返回与指定 key 关联的 值或
  • 如果 key 没有关联的值,则返回 null

注意:如果 remappingFunction 的结果为 null,则会移除指定 key 的映射。

示例 1:Java HashMap 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("Shirt 的价格: " + shirtPrice);

// 打印更新后的 HashMap
System.out.println("更新后的 HashMap: " + prices);
}
}

输出

HashMap: {Pant=150, Bag=300, Shoes=200}
Shirt 的价格: 280
更新后的 HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}

在上面的示例中,我们创建了一个名为 prices 的 hashmap。注意这个表达式,

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

这里,

  • key -> 280 是一个 lambda 表达式。它返回值 280。要了解更多关于 lambda 表达式的信息,请访问 Java Lambda 表达式
  • prices.computeIfAbsent() 将 lambda 表达式返回的新值与 Shirt 的映射关联。之所以可能,是因为 Shirt 在 hashmap 中还没有映射到任何值。

示例 2:如果键已经存在时 computeIfAbsent() 的行为

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("Shoes 的价格: " + shoePrice);

// 打印更新后的 HashMap
System.out.println("更新后的 HashMap: " + prices);
}
}

输出

HashMap: {Pant=150, Bag=300, Shoes=180}
Shoes 的价格: 180
更新后的 HashMap: {Pant=150, Bag=300, Shoes=180}

在上面的示例中,Shoes 的映射已经在 hashmap 中存在。因此,computeIfAbsent() 方法不会为 Shoes 计算新值。

推荐阅读