computeIfPresent()
方法的语法是
hashmap.computeIfPresent(K key, BiFunction remappingFunction)
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) {
// create an HashMap
HashMap<String, Integer> prices = new HashMap<>();
// insert entries to the HashMap
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// recompute the value of Shoes with 10% VAT
int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
System.out.println("Price of Shoes after VAT: " + shoesPrice);
// print updated 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 的哈希表。请注意表达式:
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 已经在哈希表中映射了一个值。
在这里,lambda 表达式充当重映射函数。它接受两个参数。
注意:如果哈希表中不存在该键,则无法使用 computeIfPresent()
方法。
另请阅读