https://www.baeldung.com/java-priorityqueue A good tutorial. You use a comparator for the objects you add to the queue, to define the order. There are methods to add or remove items or just to peek what the latest high priority item is. If you’re intended to use it concurrently you can use a PriorityBlockingQueue which is thread safe. Answer from bigkahuna1uk on reddit.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 8 )
3 weeks ago - Java™ Platform Standard Ed. 8 ... An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-in-java
PriorityQueue in Java - GeeksforGeeks
A PriorityQueue in Java is a queue where elements are ordered based on their priority, rather than the order of insertion.
Published   2 weeks ago
🌐
Baeldung
baeldung.com › home › java › java collections › guide to java priorityqueue
Guide to Java PriorityQueue | Baeldung
January 8, 2024 - Every retrieval operation of the queue (poll, remove, or peek) reads the head of the queue. Internally, the PriorityQueue relies on an array of objects. This array is automatically resized if the initial specified capacity (11 by default in JDK 17) is not enough to store all the items. While it’s not mandatory to give an initial capacity to a PriorityQueue, if we already know the size of our collection, it’s possible to avoid automatic resizes, which consume CPU cycles that we’d be better off saving. In the Javadoc, it’s specified that this implementation takes O(log(n)) time for the enqueuing and dequeuing methods (offer, poll, remove and add).
🌐
Reddit
reddit.com › r/javahelp › how can i implement a priority queue in java for task scheduling?
r/javahelp on Reddit: How can I implement a priority queue in Java for task scheduling?
January 29, 2026 -

I'm developing a Java application that requires efficient task scheduling based on priority. I want to implement a priority queue to manage tasks, where higher priority tasks are processed before lower priority ones. I've researched the `PriorityQueue` class in the Java Collections Framework, but I'm unsure how to properly implement and utilize it for my specific use case. My main concerns are how to define the priority of tasks, how to add and remove tasks from the queue, and how to ensure that tasks are processed in the correct order. Additionally, I would like to know if there are any best practices for handling edge cases, such as tasks with the same priority. Any guidance, code snippets, or resources would be greatly appreciated!

🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › › › java.base › java › util › PriorityQueue.html
PriorityQueue (Java SE 11 & JDK 11 )
January 20, 2026 - An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java priority queue (+ comparator example)
Java Priority Queue (+ Comparator Example)
August 4, 2023 - Java PriorityQueue is an unbounded Queue implementation that processes the items based on priorities. Custom ordering can be enforced with a Comparator.
🌐
Javapapers
javapapers.com › java › java-priorityqueue
Java PriorityQueue - Javapapers
PriorityQueue belongs to the Java Collections Framework. PriorityQueue is based on priority heap and it is an implementation of Queue interface. This data structure can be used when we need a Queue implementation and we have a requirement to maintain the elements of that collection in a specific sorted order based on each element’s priority.
Find elsewhere
🌐
Medium
medium.com › @greekykhs › all-about-priorityqueue-in-java-d5220dee7feb
A Guide to PriorityQueue in Java. What is PriorityQueue in Java? | by Himaanshu Shukla | Medium
July 6, 2024 - A queue follows First-In-First-Out algorithm, in case of PriorityQueue queue elements are processed according to the priority (ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation). The PriorityQueue is based on the priority heap. We can’t create PriorityQueue of Objects that are non-comparable Inserting null into a PriorityQueue will throw a NullPointerException, as PriorityQueue in Java does not permit null elements.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › concurrent › PriorityBlockingQueue.html
PriorityBlockingQueue (Java Platform SE 8 )
March 16, 2026 - Creates a PriorityBlockingQueue containing the elements in the specified collection. If the specified collection is a SortedSet or a PriorityQueue, this priority queue will be ordered according to the same ordering.
🌐
Redisson
redisson.pro › glossary › java-priority-queue.html
What is a Java priority queue? | Redisson
The business could insert each customer into a priority queue, where the priority is the amount of money that the customer has spent so far with the business. When a customer support agent becomes available, he or she can then pop the head of the queue, representing the most valuable customer with a request. In Java, priority queues are implemented using the java.util.PriorityQueue class.
🌐
Medium
medium.com › @AlexanderObregon › javas-priorityqueue-peek-method-explained-44363f4fd1c0
Java’s PriorityQueue.peek() Method Explained | Medium
January 9, 2025 - The PriorityQueue class in Java is a part of the java.util package and provides a way to manage elements in a priority-based order. The peek() method is a simple yet important feature of this class.
Top answer
1 of 13
488

Use the constructor overload which takes a Comparator<? super E> comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)

As has been said elsewhere: offer and add are just different interface method implementations. In the JDK source I've got, add calls offer. Although add and offer have potentially different behaviour in general due to the ability for offer to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue which is unbounded.

Here's an example of a priority queue sorting by string length:

// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0) {
            System.out.println(queue.remove());
        }
    }
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {
    @Override
    public int compare(String x, String y) {
        // Assume neither string is null. Real code should
        // probably be more robust
        // You could also just return x.length() - y.length(),
        // which would be more efficient.
        if (x.length() < y.length()) {
            return -1;
        }
        if (x.length() > y.length()) {
            return 1;
        }
        return 0;
    }
}

Here is the output:

short

medium

very long indeed

2 of 13
108

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

🌐
HappyCoders.eu
happycoders.eu › algorithms › priorityqueue-java
Java PriorityQueue (+ Code Examples)
November 27, 2024 - The time required for enqueue and dequeue operations in the Java PriorityQueue is equal to the time required to insert and extract from a heap. Thus, the time complexity for both operations is: O(n log n) By using a heap, the element with the highest priority is always automatically at the head of the queue and can be taken out in constant time.
🌐
Scaler
scaler.com › home › topics › java priority queue
Java Priority Queue - Scaler Topics
December 20, 2022 - Java Priority Queue is a class that implements the Queue interface in Java. It is a special type of queue where each element is associated with a priority and is sorted based on its priority.
🌐
Codecademy
codecademy.com › docs › java › priorityqueue
Java | PriorityQueue | Codecademy
May 11, 2025 - The elements are prioritized with the least value element at the head of the queue, and the Queue methods .peek() and .poll() operate on that element. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more! ... Learn to code in Java ...
🌐
Medium
medium.com › @bolot.89 › java-collection-framework-priorityqueue-queue-bfc7416fabe8
Java Collection Framework —PriorityQueue (Queue) | by Bolot Kasybekov | Medium
November 30, 2024 - In this blog, we’ll break down what a PriorityQueue is, how it works, and how you can leverage it in your projects. ... A PriorityQueue is a data structure that processes elements based on their priority rather than their insertion order.
🌐
LMU
cs.lmu.edu › ~ray › notes › pqueues
Priority Queues
There’s already a PriorityQueue class in the Java Core API. It implements the Queue interface, and has the following characteristics:
🌐
iO Flood
ioflood.com › blog › java-priority-queue
Java PriorityQueue: Ordering and Organizing Elements
March 11, 2024 - To use a priority queue in Java, you create an instance of PriorityQueue as follows: PriorityQueue<Integer> pq = new PriorityQueue<>();. Once elements are added, they will be ordered based on their natural ordering or by a Comparator provided ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.util.priorityqueue
PriorityQueue Class (Java.Util) | Microsoft Learn
An unbounded priority Queue queue based on a priority heap. [Android.Runtime.Register("java/util/PriorityQueue", DoNotGenerateAcw=true)] [Java.Interop.JavaTypeParameters(new System.String[] { "E" })] public class PriorityQueue : Java.Util.AbstractQueue, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ISerializable