computeIfPresent()

本页内容

Java HashMap computeIfPresent() 方法

Java HashMap

computeIfPresent() 方法对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。

computeIfPresent() 方法的语法为:

hashmap.computeIfPresent(K key, BiFunction remappingFunction)

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

参数说明:

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

返回值

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

==

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


示例

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

        // 重新计算鞋加上10%的增值税后的价值

        int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);

        System.out.println("Price of Shoes after VAT: " + shoesPrice);

        // 输出更新后的HashMap

        System.out.println("Updated HashMap: " + prices);

    }

}

执行以上程序输出结果为:

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shoes after VAT: 220
Updated HashMap: {Pant=150, Bag=300, Shoes=220}}

在以上实例中,我们创建了一个名为 prices 的 HashMap。

注意表达式:

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

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

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

Java HashMap

此页面最后编辑于2022年8月17日 (星期三) 17:04。