Iterating over a Queue in Java Example


The example in this section shows various ways of iterating over a Queue:
  • Iterate over a Queue using Java 8 forEach() method.
  • Iterate over a Queue using iterator().
  • Iterate over a Queue using iterator() and Java 8 forEachRemaining() method.
  • Iterate over a Queue using a simple for-each loop.
  • The iteration order in a Queue is the same as the insertion order.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Iterate over Queue with different approaches.
 * @author javaguides.net
 *
 */

public class IterateOverQueueExample {
    public static void main(String[] args) {
        Queue<String> elementsQueue = new LinkedList<>();

        elementsQueue.add("element1");
        elementsQueue.add("element2");
        elementsQueue.add("element3");
        elementsQueue.add("element4");

        System.out.println("=== Iterating over a Queue using Java 8 forEach() ===");
        elementsQueue.forEach(name -> {
            System.out.println(name);
        });

        System.out.println("\n=== Iterating over a Queue using iterator() ===");
        Iterator<String> elementQueueIterator = elementsQueue.iterator();
        while (elementQueueIterator.hasNext()) {
            String name = elementQueueIterator.next();
            System.out.println(name);
        }

        System.out.println("\n=== Iterating over a Queue using iterator() and Java 8 forEachRemaining() ===");
        elementQueueIterator = elementsQueue.iterator();
        elementQueueIterator.forEachRemaining(name -> {
            System.out.println(name);
        });

        System.out.println("\n=== Iterating over a Queue using simple for-each loop ===");
        for(String name: elementsQueue) {
            System.out.println(name);
        }
    }
}
Output:
=== Iterating over a Queue using Java 8 forEach() ===
element1
element2
element3
element4

=== Iterating over a Queue using iterator() ===
element1
element2
element3
element4

=== Iterating over a Queue using iterator() and Java 8 forEachRemaining() ===
element1
element2
element3
element4

=== Iterating over a Queue using simple for-each loop ===
element1
element2
element3
element4

Reference


Comments