Java HashMap replaceAll(BiFunction)方法及示例
HashMap类 的 replaceAll(BiFunction) 方法用给定的函数(执行某种操作)在相应的值上的结果替换每个值。这个过程以同样的方式继续进行,直到所有的条目都被处理完,或者直到函数抛出一个异常。它重新抛出由替换函数抛出的异常。
语法
default void replaceAll(BiFunction<K, V> function)
参数
- BiFunction: 对每个条目的值进行操作的函数。
返回值: 在原地替换计算值,该方法不返回任何东西。
异常情况
- ClassCastException: 被抛出,表示替换类试图将一个对象投给一个子类,而这个子类的类型不被这个Map所接受。
例子: 当一个人试图将一个Integer投给一个String,而String不是Integer的子类,将抛出一个ClassCastException。 - ConcurrentModificationException: 当一个对象被遍历时,试图同时被修改或删除,就会发生这种情况。
例子: 当一个线程(程序中独立的执行路径)在其他线程遍历一个集合时,是不允许修改的。发生这种情况的原因是上述操作的结果变得无法定义。 - IllegalArgumentException (可选) : 当替换值的某些属性被传递了一个非法或不恰当的参数,所以阻止了它被存储在这个Map中。
例子: 如果一个方法需要一个非空的字符串作为参数,而输入的字符串等于空,就会抛出IllegalArgumentException。 - NullPointerException (可选) : 当给定的函数指向null或者newValue还没有被初始化,从而指向null时,会抛出一个NullPointerException。
例子: 调用一个null对象的实例方法。 - UnsupportedOperationException (可选) : 抛出,表示请求的操作不被这个Map支持。
例子: 在ArraysList类中,如果我们使用add或remove方法,会抛出UnsupportedOperationException。
下面的程序说明了merge(Key, Value, BiFunctional)方法。
程序1 :
// Java program to demonstrate
// replaceAll(BiFunction) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap having some entries
HashMap<String, Integer>
map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
map1.put("key3", 3);
map1.put("key4", 4);
// print map details
System.out.println("HashMap1: "
+ map1.toString());
// replace oldValue with square of oldValue
// using replaceAll method
map1.replaceAll((key, oldValue)
-> oldValue * oldValue);
// print new mapping
System.out.println("New HashMap: "
+ map1);
}
}
输出:
HashMap1: {key1=1, key2=2, key3=3, key4=4}
New HashMap: {key1=1, key2=4, key3=9, key4=16}
程序2
// Java program to demonstrate
// replaceAll(BiFunction) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap having
// record of the year of birth
HashMap<String, Integer>
map1 = new HashMap<>();
map1.put("Tushar", 2000);
map1.put("Anushka", 2001);
map1.put("Sanskriti", 2003);
map1.put("Anuj", 2002);
// print map details
System.out.println("HashMap1: "
+ map1.toString());
// replace yearOfBirth with current age
// using replaceAll method
map1.replaceAll((key, yearOfBirth)
-> 2019 - yearOfBirth);
// print new mapping
System.out.println("New HashMap: "
+ map1);
}
}
输出:
HashMap1: {Sanskriti=2003, Anushka=2001, Tushar=2000, Anuj=2002}
New HashMap: {Sanskriti=16, Anushka=18, Tushar=19, Anuj=17}
参考资料: https://docs.oracle.com/javase/10/docs/api/java/util/Map.html#replaceAll(java.util.function.BiFunction)。