Java HashMap compute() 方法
compute()
方法的语法是:
hashmap.compute(K key, BiFunction remappingFunction)
这里,hashmap
是 HashMap
类的一个对象。
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) {
// 创建一个 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 的值,打九折
int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
System.out.println("Shoes 打折后的价格: " + newPrice);
// 打印更新后的 HashMap
System.out.println("更新后的 HashMap: " + prices);
}
}
输出
HashMap: {Pant=150, Bag=300, Shoes=200}
Shoes 打折后的价格: 180
更新后的 HashMap: {Pant=150, Bag=300, Shoes=180}
在上面的示例中,我们创建了一个名为 prices
的 hashmap。注意表达式,
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 表达式作为接受两个参数的重映射函数。
注意:根据 Java 的官方文档,HashMap merge() 方法比 compute()
方法更简单。
推荐阅读
- HashMap computeIfAbsent() - 如果指定的键没有映射到任何值,则计算值
- HashMap computeIfPresent() - 如果指定的键已经映射到一个值,则计算值