在本文中,我们将学习 Java ConcurrentHashMap
类的 computeIfAbsent()
方法。
找到 computeIfAbsent
方法的 Java 文档。
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
1. 如果指定的键不存在,mappingFunction 会计算一个值并将这个新的键/值添加到映射中。
2. 如果指定的键已经存在,则不计算 mappingFunction 并且映射中没有变化。
3. 如果指定的键不存在,并且 mappingFunction 将值计算为 null,则不会将此新键/值添加到映射中。
4. 整个方法调用以原子方式执行。
5. 映射函数在计算过程中不得修改此映射。
6。参数 :
key - 关联值的键。
mappingFunction - 计算值的函数。
7。返回:计算后的新值或 null。
8。异常:
NullPointerException:如果指定的键或提供的 mappingFunction 为空。
IllegalStateException:如果计算是递归的。
RuntimeException:如果 mappingFunction 抛出 RuntimeException
。
ComputeIfAbsent1.java
package com.concretepage;
import java.util.concurrent.ConcurrentHashMap;
public class ComputeIfAbsent1 {
public static void main(String[] args) {
ConcurrentHashMap<Integer, String> conMap = new ConcurrentHashMap<>();
conMap.put(10, "Varanasi");
conMap.put(20, "Prayag");
conMap.put(30, "Ayodhya");
System.out.println("--- key is present ---");
String v1 = conMap.computeIfAbsent(20, k -> k + " - Kanyakumari");
System.out.println("v1: " + v1);
System.out.println(conMap); // No change
System.out.println("--- key is not present but value is null ---");
String v2 = conMap.computeIfAbsent(40, k -> null);
System.out.println("v2: " + v2);
System.out.println(conMap); // No change
System.out.println("--- key is not present ---");
String v3 = conMap.computeIfAbsent(50, k -> k + " - Kanyakumari");
System.out.println("v3: " + v3);
System.out.println(conMap); // New entry added
}
}
输出
--- key is present ---
v1: Prayag
{20=Prayag, 10=Varanasi, 30=Ayodhya}
--- key is not present but value is null ---
v2: null
{20=Prayag, 10=Varanasi, 30=Ayodhya}
--- key is not present ---
v3: 50 - Kanyakumari
{50=50 - Kanyakumari, 20=Prayag, 10=Varanasi, 30=Ayodhya}
ComputeIfAbsent2.java
package com.concretepage;
import java.util.concurrent.ConcurrentHashMap;
public class ComputeIfAbsent2 {
public static void main(String[] args) {
ConcurrentHashMap<Integer, Integer> conMap = new ConcurrentHashMap<>();
conMap.put(10, 100);
conMap.put(20, 200);
conMap.put(30, 300);
System.out.println("--- key is present ---");
Integer v1 = conMap.computeIfAbsent(20, k -> k * 10);
System.out.println("v1: " + v1);
System.out.println(conMap); // No change
System.out.println("--- key is not present but value is null ---");
Integer v2 = conMap.computeIfAbsent(40, k -> null);
System.out.println("v2: " + v2);
System.out.println(conMap); // No change
System.out.println("--- key is not present ---");
Integer v3 = conMap.computeIfAbsent(50, k -> k * 10);
System.out.println("v3: " + v3);
System.out.println(conMap); // New entry added
}
}
输出
--- key is present ---
v1: 200
{20=200, 10=100, 30=300}
--- key is not present but value is null ---
v2: null
{20=200, 10=100, 30=300}
--- key is not present ---
v3: 500
{50=500, 20=200, 10=100, 30=300}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.concretepage.com/java/java-concurrenthashmap-computeifabsent
内容来源于网络,如有侵权,请联系作者删除!