Java HashTable compute()方法及示例
Hashtable类的 compute(Key, BiFunction) 方法允许为指定的键和其当前的映射值计算一个映射(如果没有找到当前的映射,则为空)。
- 如果在Hashtable的compute()中传递的重映射函数的返回值为null,那么该映射将从Hashtable中移除(如果最初没有,则保持不存在)。
- 如果重映射函数抛出一个异常,该异常被重新抛出,并且当前的映射保持不变。
- 在计算过程中,不允许使用此方法修改此映射。
- 计算()方法可以用来更新Hashtable里面的一个现有值。
例如,这个映射追加了映射的字符串值。
Hashtable.compute(key, (k, v) -> v.append("strValue"))
- 如果重映射函数在计算过程中修改了这个地图,这个方法将抛出一个ConcurrentModificationException。
语法
public V
compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
参数: 该方法接受两个参数。
- key :将与该值关联的键。
- remappingFunction :对值进行操作的函数。
返回: 该方法返回 与指定键相关联的新值,如果没有, 则返回 空值。
异常: 这个方法会抛出。
- ConcurrentModificationException :如果检测到重映射函数修改了这张Map。
下面的程序说明了 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 {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map<Integer, String> table = new Hashtable<>();
table.put(1, "100RS");
table.put(2, "500RS");
table.put(3, "1000RS");
// print map details
System.out.println("hashTable: "
+ table.toString());
// remap the values of hashTable
// using compute method
table.compute(3, (key, val)
-> val.substring(0, 4) + "00RS");
table.compute(2, (key, val)
-> val.substring(0, 2) + "$");
// print new mapping
System.out.println("new hashTable: " + table);
}
}
输出:
hashTable: {3=1000RS, 2=500RS, 1=100RS}
new hashTable: {3=100000RS, 2=50$, 1=100RS}
参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/Hashtable.html#compute(K, java.util.function.BiFunction)
极客教程