Java HashMap computeIfPresent(key, BiFunction)方法及示例
HashMap类的 computeIfPresent(Key, BiFunction) 方法允许你计算指定键的映射值,如果键已经与一个值相关联(或被映射为null)。
- 如果此方法的映射函数返回null,则映射被删除。
- 如果重映射函数抛出一个异常,该异常会被重新抛出,而映射则保持不变。
- 在计算过程中,不允许使用此方法修改此映射。
语法
public Object computeIfPresent(Object key,
BiFunction remappingFunction)
参数: 该方法接受两个参数。
- key :将与该值关联的键。
- remappingFunction :对值进行操作的函数。
返回: 该方法返回 与指定的键相关联的新的重映射值,如果映射返回空,则返回空
下面的程序说明了 computeIfPresent(Key, BiFunction) 方法。
例子1:这个例子演示了当键不在hashhmap中的情况。
// 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<String, Integer> 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:这个例子展示了密钥存在于哈希姆表中的情况。
// 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<String, Integer> 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://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#computeIfPresent-K-java.util.function.BiFunction-