Course contentsShow
← Java
Lesson 1182 of 2,87027. Queue and Deque ImplementationsFree lesson

LinkedList Queue Iteration Patterns

Iterating through a LinkedList used as a Queue while understanding element order and removal behavior.

LinkedList Queue Iteration Patterns

You'll learn how to iterate through a LinkedList-as-Queue while respecting FIFO order and understanding the effects of removal operations.

The Core Idea

When you iterate through a LinkedList used as a Queue, you traverse elements in the order they were added (FIFO: first in, first out). However, there are different iteration patterns depending on whether you need to consume (remove) elements or just inspect them.

Think of a queue at a coffee shop: you can either walk alongside the line looking at everyone without disturbing the order (inspection), or you can call people forward one-by-one until the line is empty (consumption).

Inspection Iteration Pattern

Use a standard for-each loop or iterator when you want to examine all elements without removing them:

Queue<String> queue = new LinkedList<>();
queue.offer("first");
queue.offer("second");
queue.offer("third");

// Inspect without removing
for (String item : queue) {
    System.out.println(item);  // first, second, third
}
// Queue still has all 3 elements

Consumption Iteration Pattern

Use poll() in a while loop when you want to process and remove elements in FIFO order:

// Process and remove each element
while (!queue.isEmpty()) {
    String item = queue.poll();
    System.out.println("Processing: " + item);
}
// Queue is now empty

This pattern is common for task processing—each iteration removes the front element until the queue is drained.

Element Order Guarantee

Both patterns respect insertion order. The iterator traverses from head (oldest element) to tail (newest element), matching the order in which poll() would retrieve them.

Key Takeaway: Use for-each to iterate without removing elements; use while (!isEmpty()) with poll() to consume the queue in FIFO order—both respect insertion order but have drastically different side effects.