當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。