Iterate through Queue in Java

In this post, we will discuss various methods to iterate through 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:

Java

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.

Java

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:

Java

Download   Run Code

3. Java 8 – using Streams

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

Java

Download   Run Code

4. Converting Queue to Array

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

Java

Download   Run Code

5. Using Enumeration Interface

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

Java

Download   Run Code

6. Using Queue.toString()

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

Java

Download   Run Code

Output:

[1, 2, 3]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz