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

Answer from Jon Skeet on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 8 )
3 weeks ago - Creates a PriorityQueue containing the elements in the specified collection. If the specified collection is an instance of a SortedSet or is another PriorityQueue, this priority queue will be ordered according to the same ordering.
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-in-java
PriorityQueue in Java - GeeksforGeeks
PriorityQueue extends AbstractQueue and implements the Queue interface, which is part of the Collection hierarchy. It also supports iteration through Iterable ... This method creates a PriorityQueue with the default initial capacity (11) that ...
Published   2 weeks ago
🌐
Stack Overflow
stackoverflow.com › questions › 29841988 › java-priority-queue-and-constructors-and-type
collections - Java/Priority queue and constructors and type - Stack Overflow
ImplementPriorityQueue is the actual type of the object, in this case a sub-class of PriorityQueue. new ImplementPriorityQueue<D>(K + 1) causes the instantiation of the object assigned to myList, using the constructor with the signature ImplementPriorityQueue(int). Incidentally, why are you calling a queue myList?
🌐
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 - Creates a PriorityQueue containing the elements in the specified collection. If the specified collection is an instance of a SortedSet or is another PriorityQueue, this priority queue will be ordered according to the same ordering.
🌐
Baeldung
baeldung.com › home › java › java collections › guide to java priorityqueue
Guide to Java PriorityQueue | Baeldung
January 8, 2024 - First, we‘ll see the standard usage and present some examples by ordering the queue in natural and inverse order. Finally, we’ll see how it’s possible to define a custom order using Java Comparators. The java.util.PriorityQueue class was provided starting from the JDK 1.5, which also contains other implementations of the AbstractQueue.
🌐
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.
🌐
Medium
medium.com › @kavya1234 › introduction-to-priority-queue-in-java-50503c4b2248
Introduction to Priority Queue in Java | by Kavya | Medium
March 2, 2025 - 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. No fixed capacity: The priority queue can grow as needed, with dynamic resizing. Null elements are not permitted: Adding a null element will throw a NullPointerException. The PriorityQueue class can be instantiated using different constructors ...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 47041503 › priority-queue-constructors-java
Priority Queue Constructors Java - Stack Overflow
public class PQueue<T> { private PQueueItem<T> head; public static enum ORDER { ASC, DESC; } public static ORDER DEFAULT_ORDER; private ORDER order; /** * The default constructor for a PQueue, with the default order for priorities */ public ...
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.

🌐
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.
🌐
Programiz
programiz.com › java-programming › priorityqueue
Java PriorityQueue
The PriorityQueue class provides the implementation of all the methods present in the Queue interface. add() - Inserts the specified element to the queue. If the queue is full, it throws an exception. offer() - Inserts the specified element to the queue. If the queue is full, it returns false.
🌐
TutorialsPoint
tutorialspoint.com › java › util › java_util_priorityqueue.htm
Java PriorityQueue Class
A priority queue relying on natural ordering also does not permit insertion of non-comparable objects. The following is the declaration for java.util.PriorityQueue class −
🌐
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);
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... 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.
🌐
LogicBig
logicbig.com › how-to › code-snippets › jcode-java-collections-priorityqueue-priorityqueue.html
Java Collections - PriorityQueue Constructors Examples
package com.logicbig.example.priorityqueue; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class PriorityQueueExample7 { public static void main(String... args) { SortedSet<Integer> set = new TreeSet<>(Comparator.reverseOrder()); for (int i = 0; i < 5; i++) { set.add(ThreadLocalRandom.current().nextInt(10, 100)); } System.out.println("the tree set: " + set); PriorityQueue<Integer> pq = new PriorityQueue<>(set); System.out.println("the priority queue: " + pq); } }
🌐
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.
🌐
Princeton University
algs4.cs.princeton.edu › 24pq
Priority Queues
April 24, 2022 - To complete the API, we also need to add constructors and a test if empty operation. For flexibility, we use a generic implementation with a generic type Key that implements Comparable. Program TopM.java is a priority queue client that takes a command-line argument M, reads transactions from ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › priority-queue-java
Priority Queue Java | DigitalOcean
August 4, 2022 - The java.util.PriorityQueue class, ... queue. It was introduced in Java 1.5 and enhanced in Java SE 8 release. PriorityQueue is internally implemented by following “Priority Heap” data structure....
🌐
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...