Hashtable类的forEach(BiConsumer)方法对哈希表的每个条目执行BiConsumer操作,直到已处理完所有条目或该操作引发异常。 BiConsumer操作是按迭代顺序执行的哈希表键值对的函数操作。方法遍历Hashtable的每个元素,直到该方法处理完所有元素或发生异常为止。操作抛出的异常将传递给调用方。
用法:
public void
forEach(BiConsumer super K, ? super V> action)
参数:此方法采用参数名称BiConsumer,该参数名称表示要对每个元素执行的操作。
返回值:此方法不返回任何内容。
异常:该方法抛出:
NullPointerException:如果指定的操作为null。
以下示例程序旨在说明forEach(BiConsumer)方法:
示例1:
// Java program to demonstrate
// forEach(BiConsumer) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map
table = new Hashtable<>();
table.put("Pen", 10);
table.put("Book", 500);
table.put("Clothes", 400);
table.put("Mobile", 5000);
table.put("Booklet", 2500);
// add 100 in each value using forEach()
table.forEach((k, v) -> {
v = v + 100;
table.replace(k, v);
});
// print new mapping using forEcah()
table.forEach(
(k, v) -> System.out.println("Key : " + k + ", Value : " + v));
}
}
输出:
Key : Booklet, Value : 2600
Key : Clothes, Value : 500
Key : Mobile, Value : 5100
Key : Pen, Value : 110
Key : Book, Value : 600
示例2:显示NullPointerException
// Java program to demonstrate
// forEach(BiConsumer) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map
table = new Hashtable<>();
table.put(1, "100RS");
table.put(2, "500RS");
table.put(3, "1000RS");
try {
// add 100 in each value using forEach()
table.forEach((k, v) -> {
v = v + 100;
table.put(null, v);
});
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.lang.NullPointerException
参考:https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#forEach-java.util.function.BiConsumer-