当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ConcurrentHashMap computeIfPresent()用法及代码示例


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 computeIfPresent() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。