Iterate over a Queue in Java
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.LinkedList; import java.util.Queue; class Main { // Iterate through a queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); for (Integer item: queue) { System.out.println(item); } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; class Main { // Iterate through a queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); // using Iterator to iterate through a queue Iterator<Integer> itr = queue.iterator(); // hasNext() returns true if the queue has more elements while (itr.hasNext()) { // next() returns the next element in the iteration System.out.println(itr.next()); } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; class Main { // Iterate through a queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); try { Iterator<Integer> itr = queue.iterator(); queue.add(4); while (itr.hasNext()) { System.out.println(itr.next()); } } catch (ConcurrentModificationException ex) { System.out.println(ex); } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.LinkedList; import java.util.Queue; import java.util.stream.Stream; class Main { // Iterate through a queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); // 1. get stream and use lambda expression queue.stream().forEach(S -> { System.out.println(S); }); // shorthand for the above code queue.stream().forEach(S -> System.out.println(S)); // 2. or by providing method reference queue.stream().forEach(System.out::println); // 3. queue inherit `forEach()` from `Iterable` interface queue.forEach(System.out::println); // 4. `iterator()` is inherited from `java.util.Collection` interface queue.iterator().forEachRemaining(System.out::println); // 5. Stream.of() + toArray() + forEach() Stream.of(queue.toArray()).forEach(System.out::println); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import java.util.LinkedList; import java.util.Arrays; import java.util.Queue; class Main { // Iterate over a queue in Java public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(1); q.add(2); q.add(3); // Convert queue to an array Integer[] array = null; // 1. Using `Queue.toArray(T[])` method array = q.toArray(new Integer[q.size()]); System.out.println(Arrays.toString(array)); // 2. `Queue.toArray(T[])` – without allocating any memory array = q.toArray(new Integer[0]); System.out.println(Arrays.toString(array)); // 3. Using `Queue.toArray()` method System.out.println(Arrays.toString(q.toArray())); // 4. Java 8 – Streams + method references array = q.stream().toArray(Integer[]::new); System.out.println(Arrays.toString(array)); // 5. Java 8 – Streams + lambda expressions array = q.stream().toArray(n -> new Integer[n]); System.out.println(Arrays.toString(array)); // 6. Using `FluentIterable` class from Guava library array = FluentIterable.from(q).toArray(Integer.class); System.out.println(Arrays.toString(array)); // 7. Using `Iterables` class from Guava library array = Iterables.toArray(q, Integer.class); System.out.println(Arrays.toString(array)); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.*; class Main { // Iterate through a queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); @Deprecated Enumeration<Integer> enumeration = new Vector(queue).elements(); // if enumeration contains more elements while (enumeration.hasMoreElements()) { // print the next element of the enumeration System.out.println(enumeration.nextElement()); } // `Collections.enumeration()` returns an enumeration over the // specified collection enumeration = Collections.enumeration(queue); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.LinkedList; import java.util.Queue; import java.util.stream.Stream; class Main { // Print string representation of a Queue in Java public static void main(String[] args) { Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); // 1. String representation of the queue using `toString()` System.out.println(queue.toString()); // 2. Java 8 and above Stream.of(queue.toString()) .forEach(System.out::println); } } |
Output:
[1, 2, 3]
That’s all about iterating over a Queue in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)