Java HashMap compute() 方法

Java HashMap

compute() 方法对 hashMap 中指定 key 的值进行重新计算。

compute() 方法的语法为:

hashmap.compute(K key, BiFunction remappingFunction)

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

参数说明:

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

返回值

如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。

实例

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

实例

import java.util.HashMap;

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

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

        // 重新计算鞋子打了10%折扣后的值
        int newPrice = prices.compute(“Shoes”, (key, value) -> value value * 10/100);
        System.out.println(“Discounted Price of Shoes: “ + newPrice);

        // 输出更新后的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 的 HashMap。

注意表达式:

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

代码中,我们使用了匿名函数 lambda 表达式 (key, value) -> value – value * 10/100 作为重新映射函数。

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

Java HashMap

本文来源于互联网:Java HashMap compute() 方法