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

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

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

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

句法:

public void forEach(Consumer action)

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

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

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

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

例子:

// Java Program Demonstrate forEach()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws IllegalStateException
    {
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // Add numbers to end of LinkedBlockingDeque
        LBD.add(11);
        LBD.add(22);
        LBD.add(33);
        LBD.add(44);
        LBD.add(55);
        LBD.add(66);
        LBD.add(77);
  
        // print deque
        System.out.println("Linked Blocking Deque: "
                           + LBD);
  
        System.out.println("Traversing this Deque: ");
  
        // Traverse this queue using forEach() method
        LBD.forEach((n) -> System.out.println(n));
    }
}
输出:
Linked Blocking Deque: [11, 22, 33, 44, 55, 66, 77]
Traversing this Deque: 
11
22
33
44
55
66
77

示例:2

// Java Program Demonstrate forEach()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws IllegalStateException
    {
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // Add elements to end of LinkedBlockingDeque
        LBD.add("GeeksforGeeks");
        LBD.add("Gfg");
        LBD.add("Geeks");
        LBD.add("Computer");
        LBD.add("Science");
        LBD.add("Portal");
  
        // print deque
        System.out.println("Linked Blocking Deque: "
                           + LBD);
  
        System.out.println("Traversing this deque: ");
  
        // Traverse this deque using forEach() method
        LBD.forEach((n) -> System.out.println(n));
    }
}
输出:
Linked Blocking Deque: [GeeksforGeeks, Gfg, Geeks, Computer, Science, Portal]
Traversing this deque: 
GeeksforGeeks
Gfg
Geeks
Computer
Science
Portal

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/LinkedBlockingDeque.html#forEach-java.util。函数.Consumer-