Java HashMap compute() 方法

compute() 方法的语法是

hashmap.compute(K key, BiFunction remappingFunction)

这里,hashmapHashMap 类的一个 对象


compute() 参数

compute() 方法接受 2 个参数

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

注意remappingFunction 可以接受两个参数。因此,被视为 BiFunction


compute() 返回值

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

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


示例:HashMap compute() 插入新值

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);

    // recompute the value of Shoes with 10% discount
    int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
    System.out.println("Discounted Price of Shoes: " + newPrice);

    // print updated HashMap
    System.out.println("Updated HashMap: " + prices);
  }
}

输出

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

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

prices.compute("Shoes", (key, value) -> value - value * 10/100)

这里,

  • (key, value) -> value - value * 10/100 - 这是一个 lambda 表达式。它将 Shoes 的旧值减少 10% 并返回。要了解有关 lambda 表达式的更多信息,请访问 Java Lambda 表达式
  • prices.compute() - 将 lambda 表达式返回的新值与 Shoes 的映射关联起来。

我们使用 lambda 表达式作为接受两个参数的 remapping 函数。

注意:根据 Java 官方文档,HashMap merge() 方法比 compute() 方法更简单。


另请阅读

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

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

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

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