Java.util.Hashtable 类

java.util.Hashtable.computeIfPresent() 方法用于更新 Hashtable 中的值,如果指定的键存在且非空。它尝试在给定键及其当前映射值的情况下计算新映射。如果函数返回 null,则映射将被删除。如果函数本身抛出(未经检查的)异常,则重新抛出异常,并且当前映射保持不变。

语法

public V computeIfPresent(
    K key, 
    BiFunction<? super K,? super V,? extends V> remappingFunction
)

这里,K和V是键的类型

参数

key 指定容器所维护的key
remappingFunction 指定计算值的函数。

返回值

返回与指定键关联的新值,如果没有则返回 null。

异常

不适用。

示例:

在下面的示例中,使用了 java.util.Hashtable.computeIfPresent() 方法更新给定哈希表中的值。

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);    

    //使用computeIfPresent方法更新指定键的值
    Htable.computeIfPresent(103, (k, v) -> "Sam"); 
    Htable.computeIfPresent(104, (k, v) -> "Lee"); 

    //打印哈希表
    System.out.println("Htable contains: " + Htable);  
  }
}

上述代码的输出将是:

Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
Htable contains: {104=Lee, 103=Sam, 102=Marry, 101=John}