Java HashMap computeIfAbsent()方法及示例
HashMap类 的 computeIfAbsent(Key, Function) 方法用于使用给定的映射函数计算一个给定的键的值,如果键还没有与一个值相关联(或者被映射为null),并在Hashmap中输入该计算值,否则为空。
- 如果这个方法的映射函数返回null,那么该键的映射就没有被记录。
- 在计算的时候,如果重映射函数抛出一个异常,这个异常会被重新抛出,并且没有映射被记录下来。
- 在计算过程中,不允许使用这个方法修改这个映射。
- 如果重映射函数在计算过程中修改了这个Map,这个方法将抛出一个ConcurrentModificationException。
语法
public V
computeIfAbsent(K key,
Function<? super K, ? extends V> remappingFunction)
参数: 该方法接受两个参数。
- key :我们想用映射来计算值的键。
- remappingFunction :对值进行操作的函数。
返回: 该方法返回 与指定键相关的当前(现有的或计算的)值,如果映射返回空值,则返回空值。 下面的程序说明了computeIfAbsent(Key, Function)方法:
程序1 :
// Java program to demonstrate
// computeIfAbsent(Key, Function) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap and add some values
HashMap<String, Integer> map
= new HashMap<>();
map.put("key1", 10000);
map.put("key2", 55000);
map.put("key3", 44300);
map.put("key4", 53200);
// print map details
System.out.println("HashMap:\n "
+ map.toString());
// provide value for new key which is absent
// using computeIfAbsent method
map.computeIfAbsent("key5",
k -> 2000 + 33000);
map.computeIfAbsent("key6",
k -> 2000 * 34);
// print new mapping
System.out.println("New HashMap:\n "
+ map);
}
}
输出
HashMap:
{key1=10000, key2=55000, key3=44300, key4=53200}
New HashMap:
{key1=10000, key2=55000, key5=35000, key6=68000, key3=44300, key4=53200}
程序2
// Java program to demonstrate
// computeIfAbsent(Key, Function) method.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a HashMap and add some values
HashMap<Integer, String>
map = new HashMap<>();
map.put(10, "Aman");
map.put(20, "Suraj");
map.put(30, "Harsh");
// print map details
System.out.println("HashMap:\n"
+ map.toString());
// provide value for new key which is absent
// using computeIfAbsent method
map.computeIfAbsent(40, k -> "Sanjeet");
// this will not effect anything
// because key 10 is present
map.computeIfAbsent(10, k -> "Amarjit");
// print new mapping
System.out.println("New HashMap:\n" + map);
}
}
输出
HashMap:
{20=Suraj, 10=Aman, 30=Harsh}
New HashMap:
{20=Suraj, 40=Sanjeet, 10=Aman, 30=Harsh}
参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html#computeIfAbsent(K, java.util.function.Function)