What is Java PriorityQueue and How to Use It?
🚀 What Will You Learn in This Guide?
In this guide, you will learn how to manage data in priority order using the Java PriorityQueue class.
Instead of FIFO (First In, First Out), this data structure processes items according to priority value.
You'll see its constructors, methods, time complexity, and special use of Comparator.
🧠 Technical Summary
Topic: Java PriorityQueue class and data priority management
Problem it solves: In normal queues, data is processed according to the entry order.
But in some cases (e.g. task schedulers, process priority, urgent queues),
Action must be taken according to priority.
PriorityQueue solves this problem.
Usage Steps:
- Create a PriorityQueue object.
- Add element (
add()oroffer()). - Fetch (
peek()) or remove (poll()) the highest priority element. - Define a custom
Comparatorif necessary.
⚙️ What is Java PriorityQueue?
PriorityQueue is a collection class available in Java's java.util package.
Arrange elements in natural order (e.g. alphabetical or numerical) or
Sorts with a specially designated comparator.
- By default smallest value is placed at the beginning of the queue.
- It uses Priority Heap in its internal structure.
- Introduced with Java 1.5 version and developed with Java SE 8.
- Its capacity is unlimited, but it works according to the heap-based sorting logic.
🧩 PriorityQueue Constructors
| Constructive Method | Description |
|---|---|
PriorityQueue() | Creates an empty queue with default capacity (11). |
PriorityQueue(int initialCapacity) | Creates a queue with the specified capacity. |
PriorityQueue(Comparator comp) | Creates a queue that sorts by the specified comparator. |
PriorityQueue(Collection c) | Creates a queue with elements from the specified collection. |
PriorityQueue(SortedSet c) | It creates elements from a sorted set (SortedSet). |
🔧 PriorityQueue Usage Example
import java.util.PriorityQueue;
public class GorevOncelik {
public static void main(String[] args) {
PriorityQueue<String> gorevler = new PriorityQueue<>();
gorevler.add("gorev3");
gorevler.add("gorev1");
gorevler.add("gorev2");
System.out.println("Kuyruktaki görevler: " + gorevler);
System.out.println("En yüksek öncelikli görev (peek): " + gorevler.peek());
}
}
🧠 This example makes “task1” the highest priority in alphabetical order.
🔁 Reverse (Descending) Sort
We can reverse the order direction of the queue using Comparator.reverseOrder().
import java.util.*;
public class TersOncelik {
public static void main(String[] args) {
PriorityQueue<String> tersKuyruk = new PriorityQueue<>(Comparator.reverseOrder());
tersKuyruk.add("A");
tersKuyruk.add("B");
tersKuyruk.add("C");
System.out.println("Ters sırada en öncelikli: " + tersKuyruk.peek());
}
}
🧠 In reverse order, “C” is the highest priority element.
⚡ Basic Methods
| 🧠 Method | 💡 Description |
|---|---|
| add(E e) | Adds the element to the queue. If it fails, it throws an exception. |
| offer(E e) | Adds the element, it may return false instead of error. |
| peek() | Returns the highest priority element (without removing it). |
| poll() | Fetches and removes the highest priority element. |
| contains(Object o) | Checks whether the element exists or not. |
| remove(Object o) | Removes the specified element from the queue. |
| size() | Returns the total number of elements in the queue. |
| clear() | It completely cleans the tail. |
| comparator() | Returns the custom Comparator object used. |
💡 Difference between peek() and poll()
PriorityQueue<String> kuyruk = new PriorityQueue<>();
kuyruk.add("A");
kuyruk.add("C");
kuyruk.add("B");
System.out.println("Peek: " + kuyruk.peek());
System.out.println("Poll: " + kuyruk.poll());
System.out.println("Yeni Baş: " + kuyruk.peek());
📤 Output:
Peek: A
Poll: A
Yeni Baş: B
🧠 peek() only displays, poll() fetches and deletes.
⏱️ Time Complexity
| ⚙️ Transaction | ⏱️ Time Complexity |
|---|---|
| add() / offer() / poll() | O(log n) |
| peek() | O(1) |
| contains() / remove(Object) | O(n) |
⚠️ PriorityQueue is not thread-safe. PriorityBlockingQueue should be used in multi-threaded environments.
💬 Frequently Asked Questions (FAQ)
- Does PriorityQueue work with FIFO logic?
No. It works on priority rather than FIFO. The highest priority element comes forward.
- Are the elements kept completely in order?
No. Only the highest priority element always goes first.
- What happens if I don't define a comparator?
By default elements are arranged in natural order.
- What about elements with the same priority?
In case of equal priority, it is unclear which one will take the lead (selected at random).
- Why can't I add primitive types (int, double)?
Collections hold objects. For this reason, primitive types are boxed into classes such as Integer and Double.
🧱 Alternative for Thread-Safe Use
For safe use in a multithreading environment:
import java.util.concurrent.PriorityBlockingQueue;
PriorityBlockingQueue<String> guvenliKuyruk = new PriorityBlockingQueue<>();
guvenliKuyruk.add("islem1");
guvenliKuyruk.add("islem2");
🧠 This class is the thread-safe version of PriorityQueue.
🏁 Conclusion
Java PriorityQueue is a perfect solution to process tasks or events in order of priority. Thanks to its logarithmic complexity, it works fast even on large data sets.
☁️ You can try this data structure immediately to ensure prioritized processing flow in microservices or task managers you develop on the GenixNode infrastructure!
yaml

