HashMap computeIfPresent(key, BiFunction) 方法在Java中的使用示例
HashMap类的 computeIfPresent(Key, BiFunction) 方法允许您在键已与值相关联(或映射到null)的情况下计算指定键的映射值。
- 如果此方法的映射函数返回 null,则移除该映射。
- 如果重新映射函数抛出异常,则重新抛出该异常并且保留该映射不变。
- 在计算过程中,不允许使用此方法修改此映射。
语法:
public Object computeIfPresent(Object key, BiFunction remappingFunction)
参数: 此方法接受两个参数:
- key :要关联值的键。
- remappingFunction :要对值执行操作的函数。
返回值: 此方法返回与指定键关联的 新映射的重映射值,如果映射返回 null,则返回 null 。
以下程序说明了 computeIfPresent(Key, BiFunction) 方法:
示例 1:此示例演示哈希映射中没有键的情况。
// 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-
极客教程