computeIfAbsent()
方法的语法是:
hashmap.computeIfAbsent(K key, Function remappingFunction)
这里,
hashmap 是
HashMap
类的对象。
computeIfAbsent() 参数
computeIfAbsent()
方法有两个参数:
注意: 重映射函数不能接受两个参数。
computeIfAbsent() 返回值
返回与指定键相关联的新或旧值 如果没有与 key 关联的值,则返回null
注意: 如果 remappingFunction 结果为 null,则删除指定键的映射。
示例 1: Java HashMap computeIfAbsent()
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); // compute the value of Shirt int shirtPrice = prices.computeIfAbsent("Shirt", key-> 280); System.out.println("Price of Shirt: " + shirtPrice); // print updated HashMap System.out.println("Updated HashMap: " + prices); } }
输出
HashMap: {Pant=150, Bag=300, Shoes=200} Price of Shirt: 280 Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
在上面的例子中,我们创建了一个名为
prices 的哈希图。注意表达式,
prices.computeIfAbsent("Shirt", key-> 280)
这里,
key-> 280 是一个 lambda 表达式。它返回值 280。要了解有关 lambda 表达式的更多信息,请访问 Java Lambda 表达式。
prices.computeIfAbsent() 将 lambda 表达式返回的新值与 Shirt 的映射相关联。这是唯一可能的,因为 Shirt 尚未映射到哈希图中的任何值。
示例 2: computeIfAbsent() 如果密钥已经存在
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", 180); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: " + prices); // mapping for Shoes is already present // new value for Shoes is not computed int shoePrice = prices.computeIfAbsent("Shoes", (key)-> 280); System.out.println("Price of Shoes: " + shoePrice); // print updated HashMap System.out.println("Updated HashMap: " + prices); } }
输出
HashMap: {Pant=150, Bag=300, Shoes=180} Price of Shoes: 180 Updated HashMap: {Pant=150, Bag=300, Shoes=180}
在上面的例子中,
Shoes 的映射已经存在于哈希图中。因此,
computeIfAbsent()
方法不会计算
Shoes 的新值。
推荐阅读
HashMap compute()-计算指定键的值 HashMap computeIfPresent()-如果指定的键已经映射到价值 Java HashMap merge()-执行与compute() 相同的任务