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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。