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   3 weeks ago
Discussions

How can I implement a priority queue in Java for task scheduling?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
5
1
January 29, 2026
java - How do I use a PriorityQueue? - Stack Overflow
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) : More on stackoverflow.com
🌐 stackoverflow.com
Priority queues of objects in Java - Stack Overflow
Hello Im a bit lost n the priority queues and comparator. I dont really see how to make a comparator in java So what I have is giving me a error and what I have read is no help to me http://www. More on stackoverflow.com
🌐 stackoverflow.com
priority queue - How does Java's PriorityQueue differ from a min-heap? - Stack Overflow
Why did they name PriorityQueue if you can't insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, then why was it named PriorityQueue and not Heap? More on stackoverflow.com
🌐 stackoverflow.com
🌐
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).
🌐
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.
🌐
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.
🌐
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!

Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › javas-priorityqueue-offer-method-explained-f407428b063b
Java’s PriorityQueue.offer() Method Explained | Medium
April 20, 2025 - A PriorityQueue is a special type of queue in Java that organizes elements based on priority rather than the order they were added. Unlike a regular queue, where elements come out in the same sequence they went in, a PriorityQueue keeps them ...
🌐
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.
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.

🌐
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.
🌐
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.
🌐
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.
🌐
HappyCoders.eu
happycoders.eu › algorithms › priorityqueue-java
Java PriorityQueue (+ Code Examples)
November 27, 2024 - In the last part of this tutorial series, I will show you how to implement a priority queue using a heap yourself. With the java.util.PriorityQueue class, the dequeue order results either from the elements' natural order¹ or according to a comparator¹ passed to the constructor.
Top answer
1 of 1
9

Let's look at how you're defining Comparator, because at the moment I don't think what you've written would even compile.

Comparator is an interface, meaning that you need to define a class that implements it. That is, you need to define a class that has concrete implementations of the methods described by the interface. Here, there's only one method you need to worry about - compare. (The interface also defines equals, but that's an odd choice since it's equal to the one on Object and so every class will implement this by default...)

The compare method takes two objects of the target type, and decides which one of them comes "before" the other. It returns:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So - you want to compare objects of whatever the class of your p1, p2 instances are (I'll call it MyClass). That means that you have to define a class:

class MyComparator implements Comparator<MyClass> {

    public int compare(MyClass a, MyClass b) {
        // TODO
    }
}

We know that the compare method should return a value depending on which of the MyClass arguments comes before the other one. You've said in your question that the one that comes first, is the one that has the smallest (i.e. earliest?) arrival time.

This is actually very easy, because that's the so-called natural ordering on java.util.Date objects - so you can just compare their arrival times against each other directly, as the result of that comparison is the same as the overall comparison.

Therefore the implementation of compare can simply be (assuming a sensibly-named accessor method):

public int compare(MyClass a, MyClass b) {
    return a.getStartTime().compareTo(b.getStartTime());
}

And there you go! You've just defined your own comparator, that will sort MyClass objects by start time ascending. You can use it in the priority queues similarly to what you have already:

Comparator<MyClass> comparator = new MyComparator();
PriorityQueue<MyClass> arrival = new PriorityQueue<MyClass>(10, comparator);
🌐
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: