The iterator() method of ArrayBlockingQueue class is used to returns an iterator of the same elements as this queue in a proper sequence. The elements returned from this method contains elements in order from first(head) to last(tail). The returned iterator is weakly consistent.
Syntax:
public Iterator iterator()
Return Value: The method returns the iterator having same elements as present in ArrayBlockingQueue in proper sequence.
Below programs illustrates iterator() method of ArrayBlockingQueue class:
Program 1:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 5;
ArrayBlockingQueue<Integer> queue = new
ArrayBlockingQueue<Integer>(capacity);
queue.offer(423);
queue.offer(422);
queue.offer(421);
queue.offer(420);
queue.offer(424);
System.out.println("Queue is " + queue);
Iterator iteratorValues = queue.iterator();
System.out.println("\nThe iterator values:");
while (iteratorValues.hasNext()) {
System.out.println(iteratorValues.next());
}
}
}
|
Output:
Queue is [423, 422, 421, 420, 424]
The iterator values:
423
422
421
420
424
Program 2:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 5;
ArrayBlockingQueue<String> queue = new
ArrayBlockingQueue<String>(capacity);
queue.offer("User");
queue.offer("Employee");
queue.offer("Manager");
queue.offer("Analyst");
queue.offer("HR");
System.out.println("Queue is " + queue);
Iterator iteratorValues = queue.iterator();
System.out.println("\nThe iterator values:");
while (iteratorValues.hasNext()) {
System.out.println(iteratorValues.next());
}
}
}
|
Output:
Queue is [User, Employee, Manager, Analyst, HR]
The iterator values:
User
Employee
Manager
Analyst
HR
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html#iterator
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!