CopyOnWriteArrayList的forEach()方法為Iterable的每個元素執行給定的操作,直到已處理完所有元素或該操作引發異常。
用法:
public void forEach (Consumer<E> action)
參數:此方法采取參數操作,該參數操作表示要對每個元素執行的操作。
返回值:此方法不返回任何內容。
異常:如果指定的操作為null,則此方法將引發NullPointerException。
以下示例程序旨在說明CopyOnWriteArrayList類的forEach()函數:
示例1:
// Java Program to illustrate the CopyOnWriteArrayList
// forEach() method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create object of CopyOnWriteArrayList
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
// Add elements
ArrLis.add(2);
ArrLis.add(3);
ArrLis.add(4);
ArrLis.add(7);
// Print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: "
+ ArrLis);
System.out.println("Traversing this List : ");
// Traverse this queue using forEach() method
ArrLis.forEach((n) -> System.out.println(n));
}
}
輸出:
CopyOnWriteArrayList: [2, 3, 4, 7] Traversing this List : 2 3 4 7
示例2:
// Java Program to illustrate the CopyOnWriteArrayList
// forEach() method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create object of CopyOnWriteArrayList
CopyOnWriteArrayList<String> ArrLis
= new CopyOnWriteArrayList<String>();
// Add elements
ArrLis.add("Geeks");
ArrLis.add("Gfg");
ArrLis.add("Portal");
ArrLis.add("geeksforgeeks");
// Print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: "
+ ArrLis);
System.out.println("Traversing this List : ");
// Traverse this queue using forEach() method
ArrLis.forEach((n) -> System.out.println(n));
}
}
輸出:
CopyOnWriteArrayList: [Geeks, Gfg, Portal, geeksforgeeks] Traversing this List : Geeks Gfg Portal geeksforgeeks
相關用法
- Java CopyOnWriteArrayList set()用法及代碼示例
- Java CopyOnWriteArrayList addAll()用法及代碼示例
- Java CopyOnWriteArrayList removeIf()用法及代碼示例
- Java CopyOnWriteArrayList retainAll()用法及代碼示例
- Java CopyOnWriteArrayList remove()用法及代碼示例
- Java CopyOnWriteArrayList equals()用法及代碼示例
- Java CopyOnWriteArrayList removeAll()用法及代碼示例
- Java CopyOnWriteArrayList addAllAbsent()用法及代碼示例
- Java CopyOnWriteArrayList subList()用法及代碼示例
- Java HashTable forEach()用法及代碼示例
- Java LinkedBlockingDeque forEach()用法及代碼示例
- Java CopyOnWriteArraySet forEach()用法及代碼示例
- Java LinkedTransferQueue forEach()用法及代碼示例
- Java Iterable forEach()用法及代碼示例
- Java Stream forEach()用法及代碼示例
注:本文由純淨天空篩選整理自ProgrammerAnvesh大神的英文原創作品 CopyOnWriteArrayList forEach() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。