java.util.Hashtable.computeIfAbsent() 方法用于更新 Hashtable 中的值,如果指定的键尚未与值关联(或映射为 null)。它尝试使用给定的映射函数计算其值并将其输入到此映射中,除非为 null。如果函数返回 null,则不会记录映射。如果函数本身抛出(未经检查的)异常,则重新抛出异常,并且不记录映射。
语法
public V computeIfAbsent(K key,
Function<? super K,? extends V> mappingFunction)
这里,K和V是键和值的类型分别由容器维护。
参数
key | 指定指定值所对应的key |
remappingFunction | 指定计算值的函数。 |
返回值
返回与指定键关联的当前(现有的或计算的)值,如果计算的值为 null,则返回 null。
异常
不适用。
示例:
在下面的示例中,java.util.Hashtable.computeIfAbsent() 方法用于更新给定哈希表中的值。
import java.util.*;
public class MyClass {
public static void main(String[] args) {
//创建哈希表
Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();
//填充哈希表
Htable.put(101, "John");
Htable.put(102, "Marry");
Htable.put(103, "Kim");
Htable.put(104, "Jo");
//打印哈希表
System.out.println("Htable contains: " + Htable);
//使用computeIfAbsent方法更新指定键的值
Htable.computeIfAbsent(105, k -> "Sam".concat(" Paul"));
//打印哈希表
System.out.println("Htable contains: " + Htable);
}
}
上述代码的输出将是:
Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
Htable contains: {105=Sam Paul, 104=Jo, 103=Kim, 102=Marry, 101=John}