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


Java ConcurrentHashMap forEach()用法及代碼示例


ConcurrentHashMap 類的 forEach() 方法為每個鍵值對執行給定的操作。

用法

public void forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action)

public <U> void forEach(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> transformer, Consumer<? super U> action)

參數

parallelismThreshold - 並行執行此操作所需的(估計)元素數

行動 - 行動

轉換器 - 一個返回轉換的函數。

返回

如果值被替換,則為真

拋出

NullPointerException 。

例子1

import java.util.concurrent.*; 

import java.util.*; 
  
public class  ConcurrentHashMapforeachExample1 { 
  
    public static void main(String[] args) 
    { 
          // crete a HashMap and add some values 
        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());  
        //replace the value of key k1 to 1000
        mapcon.replace("k1" , 1000);
        System.out.println("New HashMap after remove:\n "+ mapcon.toString()); //print statement
        mapcon.forEach( (k, v) -> System.out.printf("    k:%s, v:%s%n", k, v)); //foreach function
    } 
}

輸出:

New HashMap after remove:
 {k1=1000, k2=200, k3=300, k4=400}
    k:k1, v:1000
    k:k2, v:200
    k:k3, v:300
    k:k4, v:400

例子2

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapforeachExample2  {
   public static void main(String args[]) {
      
     ConcurrentHashMap<String , String>  mymap = new ConcurrentHashMap<String ,String>(); 

     ConcurrentHashMap<Integer , Integer>  mymap2 = new ConcurrentHashMap<Integer , Integer>(); 
     
      mymap2.put(1, 101);
      mymap2.put(2, 102);
      mymap2.put(3, 103);
      System.out.println(" mymap2:" +mymap2.toString());
      mymap.put("AA", "Java");
      mymap.put("BB", "angular");
      mymap.put("CC", "JavaScript");
      System.out.println(" mymap:" +mymap.toString());
      System.out.println("comparing mymap and mymap2:" +mymap.equals(mymap2));
      mymap.forEach( (k, v) -> System.out.printf("    k:%s, v:%s%n", k, v));
   }    
}

輸出:

mymap2:{1=101, 2=102, 3=103}
 mymap:{AA=Java, BB=angular, CC=JavaScript}
comparing mymap and mymap2:false
    k:AA, v:Java
    k:BB, v:angular
    k:CC, v:JavaScript




相關用法


注:本文由純淨天空篩選整理自 Java ConcurrentHashMap forEach() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。