Java HashMap computeIfPresent() 方法
computeIfPresent()
方法的语法是:
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
这里,hashmap
是 HashMap
类的一个对象。
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);
}
}