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


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


CopyOnWriteArraySet的forEach()方法是Java中的內置函數,用於遍曆此Set中的每個元素。

用法:

public void forEach (Consumer<E> action)

參數:此方法采取參數操作,該參數操作表示要對每個元素執行的操作。


返回值:此方法不返回任何內容。

異常:如果指定的操作為null,則此方法將引發NullPointerException。

以下示例程序旨在說明CopyOnWriteArraySet類的forEach()函數:

示例1:

// Java Program to illustrate the CopyOnWriteArraySet 
// forEach() method in Java 
  
import java.util.concurrent.CopyOnWriteArraySet; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create object of CopyOnWriteArraySet 
        CopyOnWriteArraySet<Integer> ArrSet 
            = new CopyOnWriteArraySet<Integer>(); 
  
        // Add elements 
        ArrSet.add(2); 
        ArrSet.add(3); 
        ArrSet.add(4); 
        ArrSet.add(7); 
        ArrSet.add(8); 
  
        // print CopyOnWriteArraySet 
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet); 
        System.out.println("Traversing this Set: "); 
  
        // Traverse this set using forEach() method 
        ArrSet.forEach((n) -> System.out.println(n)); 
    } 
}
輸出:
CopyOnWriteArraySet: [2, 3, 4, 7, 8]
Traversing this Set: 
2
3
4
7
8

示例2:

// Java Program to illustrate the CopyOnWriteArraySet 
// forEach() method in Java 
  
import java.util.concurrent.CopyOnWriteArraySet; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Create object of CopyOnWriteArraySet 
        CopyOnWriteArraySet<String> ArrSet 
            = new CopyOnWriteArraySet<String>(); 
  
        // Add elements 
        ArrSet.add("GeeksforGeeks"); 
        ArrSet.add("Geeks"); 
        ArrSet.add("Computer Science"); 
        ArrSet.add("Portal"); 
        ArrSet.add("Gfg"); 
  
        // Print CopyOnWriteArraySet 
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet); 
        System.out.println("Traversing this Set: "); 
  
        // Traverse this set using forEach() method 
        ArrSet.forEach((n) -> System.out.println(n)); 
    } 
}
輸出:
CopyOnWriteArraySet: [GeeksforGeeks, Geeks, Computer Science, Portal, Gfg]
Traversing this Set: 
GeeksforGeeks
Geeks
Computer Science
Portal
Gfg

參考: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CopyOnWriteArraySet.html#forEach-java.util.function.Consumer-



相關用法


注:本文由純淨天空篩選整理自ProgrammerAnvesh大神的英文原創作品 CopyOnWriteArraySet forEach() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。