📜  Java中的 HashMap computeIfPresent(key, BiFunction) 方法及示例

📅  最后修改于: 2022-05-13 01:54:59.270000             🧑  作者: Mango

Java中的 HashMap computeIfPresent(key, BiFunction) 方法及示例

HashMap 类computeIfPresent(Key, BiFunction)方法允许您计算指定键的映射值,如果键已经与值关联(或映射为空)。

  • 如果此方法的映射函数返回 null,则删除映射。
  • 如果重新映射函数抛出异常,则重新抛出异常,并且映射保持不变。
  • 在计算过程中,不允许使用此方法修改此映射。
  • 句法:

public Object computeIfPresent(Object key,
                  BiFunction remappingFunction)

参数:此方法接受两个参数:

  • key :与值关联的键。
  • remappingFunction : 对值进行操作的函数。

返回:此方法返回与指定键关联的新重新映射值,如果映射返回 null ,则返回 null

下面的程序说明了 computeIfPresent(Key, BiFunction) 方法:

示例 1:此示例演示了 key 不在 hashmap 中的情况。

// Java program to demonstrate
// computeIfPresent(Key, BiFunction) method.
  
import java.util.concurrent.*;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap wordCount = new HashMap<>();
        wordCount.put("Geeks", 1);
        wordCount.put("for", 2);
        wordCount.put("geeks", 3);
  
        // print HashMap details
        System.out.println("Hashmap before operation :\n "
                           + wordCount);
  
        // provide new value for keys which is present
        // using computeIfPresent method
        wordCount.computeIfPresent("Geek",
                                   (key, val) -> val + 100);
  
        // print new mapping
        System.out.println("HashMap after operation :\n "
                           + wordCount);
    }
}
输出:
Hashmap before operation :
 {geeks=3, Geeks=1, for=2}
HashMap after operation :
 {geeks=3, Geeks=1, for=2}

示例 2:此示例演示了 key 存在于 hashmap 中的情况。

// Java program to demonstrate
// computeIfPresent(Key, BiFunction) method.
  
import java.util.concurrent.*;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Create a HashMap and add some values
        HashMap wordCount = new HashMap<>();
        wordCount.put("Geeks", 1);
        wordCount.put("for", 2);
        wordCount.put("geeks", 3);
  
        // print HashMap details
        System.out.println("Hashmap before operation :\n "
                           + wordCount);
  
        // provide new value for keys which is present
        // using computeIfPresent method
        wordCount.computeIfPresent("for",
                                   (key, val) -> val + 1);
  
        // print new mapping
        System.out.println("HashMap after operation :\n "
                           + wordCount);
    }
}
输出:
Hashmap before operation :
 {geeks=3, Geeks=1, for=2}
HashMap after operation :
 {geeks=3, Geeks=1, for=3}

参考: https: Java/util/HashMap.html#computeIfPresent-K-java.util。函数.BiFunction-