This post will discuss various methods to iterate through a queue in Java.

1. Using enhanced for-loop

As Queue implements Iterable interface, we can use enhanced for-loop to loop through the queue, as shown below:

Download  Run Code

2. Using Iterator

Queue inherit iterator() method from java.util.Collection interface, which returns an iterator over the elements in this collection. Please be careful while using this method. As per Javadoc, there are no guarantees concerning the order in which the elements are returned.

Download  Run Code

 
If the queue is modified after the iterator is created except through the iterator’s own remove method, then both iterator and enhanced for-loop will throw a ConcurrentModificationException, as demonstrated below:

Download  Run Code

3. Java 8 – Using streams

In Java 8, we can loop a Queue with the help of streams, lambdas, and forEach() method, as shown below:

Download  Run Code

4. Converting queue to array

We can also convert the queue to an array using toArray() method and print it using Arrays.toString() (or iterate it). There are several other implementations of the toArray() method, as shown below:

Download Code

5. Using Enumeration Interface

We can also use the obsolete Enumeration interface to print a queue. This interface has methods to enumerate through the elements of a Vector. We can first convert the queue into a vector and then print all elements of that vector.

Download  Run Code

6. Using Queue.toString() method

If we’re only required to display the queue’s contents, the simplest way is to call the toString() method on it. It will return the string representation of the Queue, as shown below:

Download  Run Code

Output:

[1, 2, 3]

That’s all about iterating over a Queue in Java.