ArrayDeque Drains From Both Ends

Consume a two-ended work queue with ArrayDeque pollFirst and pollLast, pairing entries from both sides until the deque runs empty.

JavaCli Tooling

Code

snippet
import java.util.ArrayDeque;
import java.util.Deque;

public class RoundRobinReconciler {

    public static void main(String[] args) {
        Deque<String> queue = new ArrayDeque<>();
        queue.addLast("upload-a");
        queue.addLast("upload-b");
        queue.addLast("upload-c");
        queue.addLast("upload-d");
        queue.addLast("upload-e");

        // 两端各取一个配对消化;元素个数为奇数时队尾先取空,
        // pollLast 返回 null,所以每轮都要判空
        while (!queue.isEmpty()) {
            String first = queue.pollFirst();
            String last = queue.pollLast();
            if (last == null) {
                System.out.println("pair: [" + first + "]");
            } else {
                System.out.println("pair: [" + first + " + " + last + "]");
            }
        }

        // 同一个类当栈用:push/pop 都作用于队头
        Deque<String> undo = new ArrayDeque<>();
        undo.push("draw rect");
        undo.push("fill red");
        System.out.println("undo pop: " + undo.pop() + ", left: " + undo.peek());
    }
}

How it works

The code’s whole job belongs to the class RoundRobinReconciler and the function main.

One loop does the cycling here: while (!queue.isEmpty()).

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: public static void main(String[] args)

Output lines are prefixed (pair: [, undo pop:), which keeps the printed trace aligned with the operations that caused it.

Key statements

Deque<String> queue = new ArrayDeque<>();
Deque<String> undo = new ArrayDeque<>();
String first = queue.pollFirst();

Interactive Tools for This Topic

FAQ

What does ArrayDeque Drains From Both Ends print when run?
Running the file directly is enough — expect labeled output lines such as `pair: [`, `undo pop:`.