使用示例在Java中的HashMap computeIfAbsent()方法
HashMap类 的 computeIfAbsent(Key, Function) 方法用于利用给定的映射函数计算给定键的值,如果键尚未与值关联(或映射为null),则将计算出的值输入Hashmap,否则输入null。
- 如果此方法的映射函数返回null,则不记录该键的映射。
- 计算时,如果重新映射函数抛出异常,则重新抛出异常,并且不记录映射。
- 在计算过程中,不允许使用此方法修改此映射。
- 如果重新映射函数在计算过程中修改了此映射,则此方法将引发ConcurrentModificationException。
语法:
public V
computeIfAbsent(K key,
Function<? super K, ? extends V> remappingFunction)
参数: 此方法接受两个参数:
- key : 我们希望使用映射计算值的键。
- remappingFunction : 对值执行操作的函数。
返回值: 此方法返回 与指定键关联的当前(存在或计算)值,如果映射返回null,则返回null 。以下程序说明了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}
新的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)
极客教程