跳到主要内容

Java HashMap computeIfPresent() 方法

computeIfPresent() 方法的语法是:

hashmap.computeIfPresent(K key, BiFunction remappingFunction)

这里,hashmapHashMap 类的一个对象。

computeIfPresent() 方法的参数

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

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

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

computeIfPresent() 方法的返回值

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

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

示例 1:Java HashMap 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);

// 重新计算 Shoes 的值,增加 10% 的增值税
int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
System.out.println("增值税后 Shoes 的价格: " + shoesPrice);

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

输出

HashMap: {Pant=150, Bag=300, Shoes=200}
增值税后 Shoes 的价格: 220
更新后的 HashMap: {Pant=150, Bag=300, Shoes=220}

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

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

这里,

  • (key, value) -> value + value * 10/100 是一个 lambda 表达式。它计算并返回 Shoes 的新值。要了解更多关于 lambda 表达式的信息,请访问 Java Lambda 表达式
  • prices.computeIfPresent() 将 lambda 表达式返回的新值与 Shoes 的映射关联。这只有在 Shoes 已经在 hashmap 中映射了一个值时才可能。

这里,lambda 表达式充当重映射函数,并且接受两个参数。

注意:如果 hashmap 中不存在键,我们不能使用 computeIfPresent() 方法。

推荐阅读