Java 中的哈希表 compute() 方法及其示例

Java 中的哈希表 compute() 方法及其示例

哈希表类的 compute(Key, BiFunction) 方法允许为指定的键和其当前映射值(如果找不到当前映射,则为 null)计算映射。

  • 如果哈希表中 compute() 的重新映射函数返回 null,则将移除该映射(如果一开始没有映射,则保持缺失)。
  • 如果重新映射函数抛出异常,则会重新抛出该异常,并保留当前映射不变。
  • 在计算过程中,不允许使用此方法修改此映射。
  • compute() 方法可用于更新哈希表中的现有值。
    例如,此映射附加映射字符串值:
Hashtable.compute(key, (k, v) -> v.append("strValue"))
  • 如果重新映射函数在计算过程中修改此哈希表,则此方法将引发 ConcurrentModificationException 异常。

语法:

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

参数: 此方法接受两个参数:

  • key :要关联值的键。
  • remappingFunction :对值执行操作的函数。

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

异常: 此方法抛出:

  • ConcurrentModificationException :如果检测到重新映射函数修改了此哈希表。

以下程序说明了 compute(Key, BiFunction) 方法:

程序 1:

// Java program to demonstrate
// compute(Key, BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
  
        // create a table and add some values
        Map<String, Integer> table = new Hashtable<>();
        table.put("Pen", 10);
        table.put("Book", 500);
        table.put("Clothes", 400);
        table.put("Mobile", 5000);
  
        // print map details
        System.out.println("hashTable: " + table.toString());
  
        // remap the values of hashTable
        // using compute method
        table.compute("Pen", (key, val)
                                 -> val + 15);
        table.compute("Clothes", (key, val)
                                     -> val - 120);
  
        // print new mapping
        System.out.println("new hashTable: " + table);
    }
}
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400}
new hashTable: {Book=500, Mobile=5000, Pen=25, Clothes=280}

输出:

hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400}
new hashTable: {Book=500, Mobile=5000, Pen=25, Clothes=280}

程序 2:

// Java program to demonstrate
// compute(Key, BiFunction) method.
  
import java.util.*;
  
public class GFG {
  
    // 主方法
    public static void main(String[] args)
    {
  
        // 创建一个表并添加一些值
        Map<Integer, String> table = new Hashtable<>();
        table.put(1, "100RS");
        table.put(2, "500RS");
        table.put(3, "1000RS");
  
        // 打印表详情
        System.out.println("hashTable: "
                           + table.toString());
  
        // 使用 compute 方法重新映射 hashTable 的值
        table.compute(3, (key, val)
                             -> val.substring(0, 4) + "00RS");
        table.compute(2, (key, val)
                             -> val.substring(0, 2) + "$");
  
        // 打印新的映射
        System.out.println("new hashTable: " + table);
    }
}
hashTable: {3=1000RS, 2=500RS, 1=100RS}
new hashTable: {3=100000RS, 2=50$, 1=100RS}

References: https://docs.oracle.com/javase/10/docs/api/java/util/Hashtable.html#compute(K, java.util.function.BiFunction)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程