forEach() method of PriorityBlockingQueue in Java is used to iterate over all the elements in the PriorityBlockingQueue and perform a specific task. This method processes the elements sequentially in the order they are present in the queue. The PriorityBlockingQueue implements the Queue interface, which provides this functionality.
Example 1: The below Java program demonstrates the use of the forEach() method to iterate over and print each integer element in the PriorityBlockingQueue.
// Iterate over the elements of the
// queue and print the integer
import java.util.concurrent.PriorityBlockingQueue;
class Geeks {
public static void main(String[] args)
{
// Creating a PriorityBlockingQueue
PriorityBlockingQueue q
= new PriorityBlockingQueue();
// use add() to insert elements in the queue
q.add(20);
q.add(10);
q.add(30);
// Using forEach to print each element of the queue
System.out.println(
"Elements in PriorityBlockingQueue:");
q.forEach(e -> System.out.println(e));
}
}
Output
Elements in PriorityBlockingQueue: 10 20 30
Syntax
void forEach(Consumer action)
Parameter: action - A consumer defines what action should be performed on each element.
Example 2: The below Java program demonstrates the use of forEach() method to iterate over and print each String element in the queue.
// Iterate over the elements of the
// queue and print the string
import java.util.concurrent.PriorityBlockingQueue;
class Geeks {
public static void main(String[] args)
{
// Creating a PriorityBlockingQueue
PriorityBlockingQueue<String> q
= new PriorityBlockingQueue<>();
// use add() method to insert elements in the queue
q.add("A");
q.add("D");
q.add("C");
q.add("B");
q.add("E");
// Using forEach to print each element of the queue
System.out.println(
"Elements in PriorityBlockingQueue:");
q.forEach(s -> { System.out.println(s); });
}
}
Output
Elements in PriorityBlockingQueue: A B C D E