Java.util.Hashtable 类

java.util.Hashtable.compute() 方法用于更新哈希表中的值。它尝试计算指定键及其当前映射值的映射(如果没有当前映射,则为 null)。如果函数返回 null,则映射将被删除(或者如果最初不存在,则保持不存在)。如果函数本身抛出(未经检查的)异常,则重新抛出异常,并且当前映射保持不变。

语法

public V compute(K key, 
                 BiFunction<? super K,? super V,? extends V> remappingFunction)
  • 1
  • 2

这里,K和V是键的类型

参数

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

返回值

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

异常

不适用。

示例:

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

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

    //使用compute方法更新指定键的值
    Htable.compute(101, (k, v) -> v.concat(" Paul")); 
    Htable.compute(104, (k, v) -> "Sam"); 

    //打印哈希表
    System.out.println("Htable contains: " + Htable);  
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

上述代码的输出将是:

Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
Htable contains: {104=Sam, 103=Kim, 102=Marry, 101=John Paul}
  • 1
  • 2