ConcurrentHashMap 类的 computeIfPresent() 方法计算给定键及其当前映射值的新映射(如果指定键的值存在)。
用法
public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
参数
key- 与指定值相关联的键
remappingFunction- 计算值的函数。
返回
与指定键关联的新值,如果没有,则为 null
抛出
NullPointerException
IllegalStateException
运行时异常
例子1
//import statement
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentHashMapcomputeIfPresentExample1 {
public static void main(String[] args)
{
HashMap<String, Integer> mapcon = new HashMap<>();
mapcon.put("k1", 100);
mapcon.put("k2", 200);
mapcon.put("k3", 300);
mapcon.put("k4", 400);
System.out.println("HashMap values:\n " + mapcon.toString());
mapcon.computeIfPresent("k4", (key , val) -> val + 100);
mapcon.computeIfPresent("k5", (key , val) -> val + 100);
System.out.println("New HashMap after computeIfPresent:\n "+ mapcon);
}
}
输出:
HashMap values: {k1=100, k2=200, k3=300, k4=400} New HashMap after computeIfPresent: {k1=100, k2=200, k3=300, k4=500}
例子2
import java.util.concurrent.*;
public class ConcurrentHashMapcomputeIfPresentExample2 {
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> mapcon = new ConcurrentHashMap<>();
mapcon.put("A", 26);
mapcon.put("B", 98);
mapcon.put("C", 55);
System.out.println("ConcurrentHashMap values:\n "+ mapcon.toString());
mapcon.computeIfPresent("C", (key , val) -> val + 100);
System.out.println("new ConcurrentHashMap after computeIfPresent:\n " + mapcon);
}
}
输出:
ConcurrentHashMap values: {A=26, B=98, C=55} new ConcurrentHashMap after computeIfPresent: {A=26, B=98, C=155}
相关用法
- Java ConcurrentHashMap computeIfAbsent()用法及代码示例
- Java ConcurrentHashMap compute()用法及代码示例
- Java ConcurrentHashMap contains()用法及代码示例
- Java ConcurrentHashMap containsKey()用法及代码示例
- Java ConcurrentHashMap containsValue()用法及代码示例
- Java ConcurrentHashMap clear()用法及代码示例
- Java ConcurrentHashMap newKeySet()用法及代码示例
- Java ConcurrentHashMap elements()用法及代码示例
- Java ConcurrentHashMap forEach()用法及代码示例
- Java ConcurrentHashMap putIfAbsent()用法及代码示例
- Java ConcurrentHashMap isEmpty()用法及代码示例
- Java ConcurrentHashMap equals()用法及代码示例
- Java ConcurrentHashMap putAll()用法及代码示例
- Java ConcurrentHashMap mappingCount()用法及代码示例
- Java ConcurrentHashMap merge()用法及代码示例
- Java ConcurrentHashMap hashcode()用法及代码示例
- Java ConcurrentHashMap put()用法及代码示例
- Java ConcurrentHashMap toString()用法及代码示例
- Java ConcurrentHashMap replace()用法及代码示例
- Java ConcurrentHashMap size()用法及代码示例
注:本文由纯净天空筛选整理自 Java ConcurrentHashMap computeIfPresent() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。