🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-in-java
PriorityQueue in Java - GeeksforGeeks
It also supports iteration through Iterable ... This method creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
Published   3 weeks ago
🌐
Baeldung
baeldung.com › home › java › java collections › guide to java priorityqueue
Guide to Java PriorityQueue | Baeldung
January 8, 2024 - That’s because initializing a priority queue with a null Comparator will directly order elements using the compare operation. As an example, let’s now see that by providing a standard Integer natural ordering comparator or null, the queue will be ordered in the same way:
Discussions

How do you make Java's PriorityQueue custom sort?
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://imgur.com/a/fgoFFis ) 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
10
5
November 10, 2021
java - How do I use a PriorityQueue? - Stack Overflow
The offer method is designed for ... 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. ... The 8th version of Java was the best ... More on stackoverflow.com
🌐 stackoverflow.com
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
[Help] Trying to Understand Priority Queue
Offer is essentially the same thing as Add, it simply inserts it into the PQ. If you are wondering why the result that is printed is not in a sorted order as you might expect, read the top paragraph again: Priority Queues in Java are implemented using a Heap. Printing a Heap is different than printing an Array / ArrayList. If you implement your own PQ using an Array ( which, imo, is a good practice to try ), printing the Queue would look sorted. More on reddit.com
🌐 r/learnjava
5
4
April 30, 2015
🌐
freeCodeCamp
freecodecamp.org › news › priority-queue-implementation-in-java
Priority Queues in Java Explained with Examples
September 1, 2024 - This is a simple Java class to store customer orders. This class implements comparable interface, so that we can decide on what basis this object needs to be ordered in the priority queue.
🌐
Redisson
redisson.pro › glossary › java-priority-queue.html
What is a Java priority queue? | Redisson
For example, suppose that a business wants to answer customer support requests starting with their most valuable customers. 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.
🌐
Programiz
programiz.com › java-programming › priorityqueue
Java PriorityQueue
... import java.util.PriorityQueue; class Main { public static void main(String[] args) { // Creating a priority queue PriorityQueue<Integer> numbers = new PriorityQueue<>(); // Using the add() method numbers.add(4); numbers.add(2); System.out.println("PriorityQueue: " + numbers); // Using ...
🌐
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.
🌐
HappyCoders.eu
happycoders.eu › algorithms › priorityqueue-java
Java PriorityQueue (+ Code Examples)
November 27, 2024 - The following example shows how to create a priority queue in Java and how to write several random numbers into the queue and then take them out again (→ code on GitHub).
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › priority-queue-java
Priority Queue Java | DigitalOcean
August 4, 2022 - The java.util.PriorityQueue class, provides us an implementation of such a data type, by using priority heap implementation internally. Java PriorityQueue is an unbounded queue. It was introduced in Java 1.5 and enhanced in Java SE 8 release. PriorityQueue is internally implemented by following ...
🌐
Codecademy
codecademy.com › docs › java › priorityqueue
Java | PriorityQueue | Codecademy
May 11, 2025 - A PriorityQueue can be traversed with a for-each loop. Items will be returned in the order they were inserted, not in priority order. ... The .peek() method retrieves the head of the queue without removing it, while .poll() retrieves and removes it.
🌐
Coding Shuttle
codingshuttle.com › java-programming-handbook › java-priority-queue
Java PriorityQueue | Coding Shuttle
April 9, 2025 - Accepts a custom Comparator to define ordering. PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(30); pq.offer(10); pq.offer(20); System.out.println("PriorityQueue: " + pq);
🌐
Quora
quora.com › What-are-some-examples-of-priority-queue-in-Java
What are some examples of priority queue in Java? - Quora
Answer (1 of 4): Since version 5 Java has a built in class called PriorityQueue [1] that implements a priority queue data structure. This queue orders element according to their natural ordering [2], but it also has a constructor that allows you to pass a Comparator object into it that will orde...
🌐
Medium
medium.com › @kavya1234 › introduction-to-priority-queue-in-java-50503c4b2248
Introduction to Priority Queue in Java | by Kavya | Medium
March 2, 2025 - Elements are ordered based on priority: The highest priority element is always at the front of the queue. Min-Heap Implementation: Java’s PriorityQueue is implemented as a min-heap by default, which means the smallest element (lowest priority) appears at the head of the queue.
🌐
TutorialsPoint
tutorialspoint.com › java › util › java_util_priorityqueue.htm
Java PriorityQueue Class
The head of the queue is: 10 The removed element is: 10 The queue is: [20, 35] The following are the class constructors present in the PriorityQueue class − · The following are the supported methods in the PriorityQueue class − · This class inherits methods from the following classes in Java − ... The following example shows the usage of the Java PriorityQueue add(E) method to add Integers.
🌐
Quora
quora.com › How-is-a-priority-queue-implemented
How is a priority queue implemented? - Quora
Answer (1 of 2): A priority queue is a container adopter in STL. Given that the components are arranged in a non-decreasing order, the first element in a priority queue is always the highest element in the queue. The difference between the conventional queue, which pushes and pops the element ac...
🌐
Wikipedia
en.wikipedia.org › wiki › Priority_queue
Priority queue - Wikipedia
1 week ago - Priority values have to be instances ... respect to the given order relation. For example, in Java standard library, PriorityQueue's the least elements with respect to the order have the highest priority....
🌐
Medium
medium.com › javarevisited › how-is-the-priorityqueue-implemented-in-java-340962a8c2f5
How is the PriorityQueue implemented in Java? | by Thirupathi Pavan Sai | Javarevisited | Medium
September 20, 2025 - Queue<String> queue = new LinkedList<>(); queue.add("Pavan"); queue.add("Sai"); System.out.println(queue.remove()); // Pavan ... A humble place to learn Java and Programming better.
🌐
GitHub
gist.github.com › ff76945655fd633aa4e05d13cc5c8667
priority queue implementation in java · GitHub
priority queue implementation in java. GitHub Gist: instantly share code, notes, and snippets.
🌐
CalliCoder
callicoder.com › java-priority-queue
Java Priority Queue Tutorial with Examples | CalliCoder
February 18, 2022 - Let’s see the same example with a Priority Queue of String elements. import java.util.PriorityQueue; public class CreatePriorityQueueStringExample { public static void main(String[] args) { // Create a Priority Queue PriorityQueue<String> namePriorityQueue = new PriorityQueue<>(); // Add items to a Priority Queue (ENQUEUE) namePriorityQueue.add("Lisa"); namePriorityQueue.add("Robert"); namePriorityQueue.add("John"); namePriorityQueue.add("Chris"); namePriorityQueue.add("Angelina"); namePriorityQueue.add("Joe"); // Remove items from the Priority Queue (DEQUEUE) while (!namePriorityQueue.isEmpty()) { System.out.println(namePriorityQueue.remove()); } } }
🌐
Reddit
reddit.com › r/javahelp › how do you make java's priorityqueue custom sort?
r/javahelp on Reddit: How do you make Java's PriorityQueue custom sort?
November 10, 2021 -

I want to sort weighted edges, one of the edge's members being the edgeweight. It already implements:

 /**
     * Compares two edges by weight.
     * Note that {@code compareTo()} is not consistent with {@code equals()},
     * which uses the reference equality implementation inherited from {@code Object}.
     *
     * @param  that the other edge
     * @return a negative integer, zero, or positive integer depending on whether
     *         the weight of this is less than, equal to, or greater than the
     *         argument edge
     */
    @Override
    public int compareTo(Edge that) {
        return Double.compare(this.weight, that.weight);
    }

Which leads me to think I need to sort by Comparable, but I don't know how. I read https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html and did not find any information to help myself out.

I asked and someone said do this:

Queue<Edge> queue = new PriorityQueue<>((e1 , e2) -> e1.compareTo(e2))

I am not sure if this is the way to go, but if it is, I am not sure how this works since I am not familiar with lambda other than that they are one liner unnamed functions. I would love an explanation of how to sort by custom parameters.

Thanks

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.