当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LinkedBlockingDeque forEach()用法及代码示例


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

用法:

public void forEach(Consumer<E> action)

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


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

异常:如果指定的操作为null,则此方法将引发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<Integer> LBD 
            = new LinkedBlockingDeque<Integer>(); 
  
        // 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<String> LBD 
            = new LinkedBlockingDeque<String>(); 
  
        // 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.function.Consumer-



相关用法


注:本文由纯净天空筛选整理自ProgrammerAnvesh大神的英文原创作品 LinkedBlockingDeque forEach() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。