Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS MATH

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java OOP Visuals Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java Problem Solving

Java Problem Solving Java Build the Logic Java Test Cases

Java Projects

Java Projects

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A

Java Reference

Java Reference Java Keywords ArrayList Methods Arrays Methods BufferedReader BufferedWriter Character Methods Collections Methods Comparator Methods Date and Time Enum Methods Errors & Exceptions File Methods FileInputStream FileOutputStream FileReader FileWriter HashMap Methods HashSet Methods Integer Methods Iterator Methods LinkedHashMap Methods LinkedHashSet Methods LinkedList Methods Math Methods Optional Methods Output Methods Random Methods RegEx Methods Scanner Methods String Methods StringBuilder Methods System Methods Thread Methods TreeMap Methods TreeSet Methods


Java PriorityQueue


Java PriorityQueue

A PriorityQueue is a special kind of queue where elements with the highest priority are removed first - not necessarily the ones added first.

It is part of the java.util package and implements the Queue interface.

Tip: Think of a PriorityQueue like a hospital emergency room: the most urgent patients are treated first, even if they arrived later.

Default behavior: The smallest element (natural ordering) is given the highest priority. For example, in a queue of numbers 40, 10, 30, the number 10 is removed first.


Create a PriorityQueue

Example

Create a PriorityQueue object called numbers that will store integers:

import java.util.PriorityQueue;

PriorityQueue<Integer> numbers = new PriorityQueue<>();

Now you can use methods like add() to insert elements, peek() to look at the top priority, and poll() to remove it.


Add Elements

Use add() or offer() to insert elements:

Example

import java.util.PriorityQueue;

public class Main {
  public static void main(String[] args) {
    // Create a PriorityQueue of integers
    PriorityQueue<Integer> numbers = new PriorityQueue<>();

    // Add some elements
    numbers.add(40);
    numbers.add(10);
    numbers.add(30);
    numbers.add(20);

    System.out.println(numbers);
  }
}

Try it Yourself »



Peek and Poll

Use peek() to look at the smallest element (highest priority), and poll() to remove it:

Example

numbers.add(10);
numbers.add(30);
numbers.add(30);
numbers.add(20);

System.out.println("Top priority: " + numbers.peek());
numbers.poll(); // Remove the smallest
System.out.println("After poll: " + numbers);

Try it Yourself »


Loop Through a PriorityQueue

You can use a for-each loop to go through the elements. Note that the iteration order is not necessarily sorted. It is because a PriorityQueue maintains priority when removing elements, not when looping:

Example

numbers.add(40);
numbers.add(1);
numbers.add(10);
numbers.add(30);
numbers.add(20);
numbers.add(50);

// Loop through the elements
for (int n : numbers) {
  System.out.println(n);
}

Result:

1
20
10
40
30
50

Try it Yourself »

If you want sorted order while printing, use a while loop with poll() instead - because poll() removes and returns the smallest element each time, giving you elements in priority order:

Example

numbers.add(40);
numbers.add(1);
numbers.add(10);
numbers.add(30);
numbers.add(20);
numbers.add(50);

 // Print elements in sorted order (by priority)
while (!numbers.isEmpty()) {
  System.out.println(numbers.poll());
}

Result:

1
10
20
30
40
50

Try it Yourself »

Use a for-each loop if you just want to see the contents (in any order). Use a while loop with poll() to retrieve elements in sorted priority order.


PriorityQueue with Strings

You can also use PriorityQueue with strings:

Example

import java.util.PriorityQueue;

public class Main {
  public static void main(String[] args) {
    PriorityQueue<String> names = new PriorityQueue<>();
    names.add("John");
    names.add("Bo");
    names.add("Liam");
    names.add("Angie");

    while (!names.isEmpty()) {
      System.out.println(names.poll());
    }
  }
}

Result:

Angie
Bo
John
Liam

Try it Yourself »


When to Use PriorityQueue?

Use a PriorityQueue when you need elements to be processed by importance rather than the order they were added.

Some common use cases:

  • Task scheduling (e.g., urgent jobs handled first)
  • Managing print queues by urgency
  • Simulating priority-based systems (like airline boarding)


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.