📌  相关文章
📜  Java中的 CopyOnWriteArrayList forEach() 方法及示例

📅  最后修改于: 2022-05-13 01:55:21.122000             🧑  作者: Mango

Java中的 CopyOnWriteArrayList forEach() 方法及示例

CopyOnWriteArrayList 的forEach()方法对 Iterable 的每个元素执行给定的操作,直到处理完所有元素或该操作引发异常。

句法:

public void forEach (Consumer action)

参数:此方法采用参数操作,该操作表示要对每个元素执行的操作。

返回:此方法不返回任何内容。

异常:如果指定的操作为空,此方法将抛出NullPointerException

下面的程序说明了 CopyOnWriteArrayList 类的 forEach()函数:

方案一:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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

方案二:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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

参考: https: Java/util/concurrent/CopyOnWriteArrayList.html#forEach-java.util。函数.Consumer-