Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue

A browser back button pops java-basics first, a waiting room polls Emma first, and an emergency room treats Ravi with urgency 1 before Meera and Emma. One question, who goes first, answered by an ArrayDeque used two ways and a PriorityQueue with a comparator.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Use an ArrayDeque as a stack with push, peek and pop
  • Use an ArrayDeque as a queue with offer, peek and poll
  • Explain how one ArrayDeque does both jobs with its two ends
  • Hand out the most urgent item first with a PriorityQueue and a comparator

Before you start

  • From arrays to collections: the framework map
  • Java sorting with Comparable and Comparator

Stacks, queues and priority queues all answer one question: who goes first? A browser back button, a waiting room and an emergency room each answer it differently.

A stack: last in, first out

package org.studyeasy.s04l11;

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

public class Ex01_StackWithDeque {
    public static void main(String[] args) {
        // Last in, first out: the browser's back button
        Deque<String> history = new ArrayDeque<>();
        history.push("home");             // the newest page goes on top
        history.push("courses");
        history.push("java-basics");

        System.out.println("History: " + history);
        System.out.println("Viewing: " + history.peek()); // look only
        System.out.println("Back from " + history.pop()); // remove
        System.out.println("Now viewing: " + history.peek());
    }
}
History: [java-basics, courses, home]
Viewing: java-basics
Back from java-basics
Now viewing: courses

The naming is a little confusing: to make a stack, you create a Deque and initialise it with new ArrayDeque. push puts a page on top, so home went in first but prints last. peek only looks at the top; nothing leaves. pop removes the top, and courses is on top again. A Deque has no index, so history.get(1) is "cannot find symbol".

A queue: first in, first out

// First in, first out: the waiting room
Queue<String> waiting = new ArrayDeque<>();
waiting.offer("Emma");          // join at the back
waiting.offer("Ravi");
waiting.offer("Meera");

System.out.println("Waiting: " + waiting);
System.out.println("Next up: " + waiting.peek()); // look only
System.out.println("Seeing " + waiting.poll());   // remove
System.out.println("Seeing " + waiting.poll());  // the next one
System.out.println("Left: " + waiting);
Waiting: [Emma, Ravi, Meera]
Next up: Emma
Seeing Emma
Seeing Ravi
Left: [Meera]

Same class, opposite order. offer joins at the back, poll takes from the front, so whoever waited longest is seen first. An ArrayDeque refuses null: waiting.offer(null) throws a NullPointerException.

Two ends, two ways to use it

An ArrayDeque holding Emma, Ravi, Meera has a front end and a back end. As a stack, push adds Kiran at the front and pop takes Kiran back from the same front end. As a queue, offer adds Asha at the back and poll takes Emma from the front. EmmaRaviMeera frontback push("Kiran") pop() / poll() offer("Asha") Stack: one end for both jobs. Queue: add at the back, take from the front.
An ArrayDeque has two ends; how you use them makes it a stack or a queue.

An ArrayDeque ("deque" is a double-ended queue) has a front and a back. As a stack, push adds at the front and pop takes from the same end, so Kiran goes in and comes straight back out. As a queue, offer adds Asha behind Meera and poll takes Emma from the front.

A PriorityQueue: most urgent first

package org.studyeasy.s04l11;

public class Patient {
    private final String name;
    private final int urgency;      // 1 = most urgent

    public Patient(String name, int urgency) {
        this.name = name;
        this.urgency = urgency;
    }

    public int getUrgency() {
        return urgency;
    }

    @Override
    public String toString() {
        return name + " (urgency " + urgency + ")";
    }
}
// Lower urgency number is treated first
Comparator<Patient> byUrgency = new Comparator<Patient>() {
    @Override
    public int compare(Patient a, Patient b) {
        return Integer.compare(a.getUrgency(), b.getUrgency());
    }
};

Queue<Patient> triage = new PriorityQueue<>(byUrgency);
triage.offer(new Patient("Emma", 3));    // strained ankle
triage.offer(new Patient("Ravi", 1));    // chest pain
triage.offer(new Patient("Meera", 2));   // high fever

while (!triage.isEmpty()) {
    System.out.println("Treating " + triage.poll());
}
Treating Ravi (urgency 1)
Treating Meera (urgency 2)
Treating Emma (urgency 3)

In an emergency room, arrival order isn't what you want. Emma arrived first with a strained ankle, which can wait. A Patient is our own object, so Java doesn't know how to compare two of them; the comparator says the lower number is more urgent. poll always hands out the most urgent one: Ravi, then Meera, then Emma. Create the PriorityQueue without the comparator and you get a ClassCastException, because Java still can't order a Patient.

Which one for which job

StackQueuePriorityQueue
Built withArrayDequeArrayDequePriorityQueue
Methodspush, peek, popoffer, peek, polloffer, poll
Comes out firstnewestoldestmost urgent
Everyday exampleback buttonwaiting roomemergency room

An AI can write this code for you, but you need to know these tools exist so you can decide who goes first.

Keep going in Java · 53 of 79

Previous
Java Maps: HashMap, LinkedHashMap and TreeMap
Next post
Choosing a Java Collection: Immutable and Sequenced Collections
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

On this page

  • A stack: last in, first out
  • A queue: first in, first out
  • Two ends, two ways to use it
  • A PriorityQueue: most urgent first
  • Which one for which job
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.