Java HashMap computeIfAbsent()

computeIfAbsent() 方法的语法是

hashmap.computeIfAbsent(K key, Function remappingFunction)

这里,hashmapHashMap 类的一个 对象


computeIfAbsent() 参数

computeIfAbsent() 方法接受 2 个参数

  • key - 要与计算值关联的键
  • remappingFunction - 用于计算指定 key 的新值的函数

注意重新映射函数 不能接受两个参数。


computeIfAbsent() 返回值

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

注意:如果 remappingFunction 返回 null,则会删除指定 key 的映射。


示例 1:Java HashMap computeIfAbsent()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // compute the value of Shirt
    int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
    System.out.println("Price of Shirt: " + shirtPrice);

    // print updated 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 的哈希表。请注意表达式:

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

这里,

  • key -> 280 是一个 lambda 表达式。它返回值为 280。要了解更多关于 lambda 表达式的信息,请访问 Java Lambda 表达式
  • prices.computeIfAbsent() 将 lambda 表达式返回的新值与 Shirt 的映射关联起来。这是可能的,因为 Shirt 已经映射到哈希表中的某个值。

示例 2:computeIfAbsent() 如果键已存在

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 180);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // mapping for Shoes is already present
    // new value for Shoes is not computed
    int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
    System.out.println("Price of Shoes: " + shoePrice);

    // print updated 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 的映射已存在于哈希表中。因此,computeIfAbsent() 方法不会为 Shoes 计算新值。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战