Java PriorityQueue
A PriorityQueue implements the Queue interface. It stores elements in a collection prioritized by natural ordering or by a custom Comparator. 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.
Creating a PriorityQueue
Using natural ordering:
import java.util.PriorityQueue;PriorityQueue<DataType> q = new PriorityQueue<DataType>();
Using a custom Comparator:
import java.util.PriorityQueue;import java.util.Comparator;PriorityQueue<DataType> q = new PriorityQueue<DataType>(new CustomComparator());
In this syntax:
q: APriorityQueuecreated with thenewkeyword.DataType: The data type to be stored inq.CustomComparator: A customComparatorforDataTypeor a parent class ofDataType.
Adding Items to PriorityQueue
The .add() method adds new items to a PriorityQueue.
Syntax
priorityqueue.add(item)
Parameters:
item: The item to be added to thepriorityqueue. It should match the data type ofpriorityqueue.
Return value:
Returns true if item is successfully added, and false otherwise.
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> result = new PriorityQueue<String>();result.add("Cabbage");result.add("Pizza");result.add("Sausage");result.add("Potatoes");result.add("Salad");return result;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();System.out.println(food);}}
Output:
[Cabbage, Pizza, Sausage, Potatoes, Salad]
Removing Items from PriorityQueue
The .remove() method removes specific items from a PriorityQueue.
Syntax
priorityqueue.remove(item)
Parameters:
item: The item to be removed frompriorityqueue. Ifitemis not found, the method has no effect.
Return value:
Returns true if item is successfully removed, and false otherwise.
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> food = new PriorityQueue<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");return food;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();food.remove("Pizza");while (food.size() > 0) {System.out.println(food.poll());}}}
Output:
CabbagePotatoesSaladSausage
Searching for an Item in PriorityQueue
The .contains() method checks whether a specific item exists in a PriorityQueue.
Syntax
priorityqueue.contains(item);
Parameters:
item: The item to search for inpriorityqueue.
Return value:
Returns true if item is found, and false otherwise.
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> food = new PriorityQueue<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");return food;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();if (food.contains("Nuts")) {System.out.println("Allergen warning!");} else {System.out.println("Safe to eat.");}}}
Output:
Safe to eat.
Returning the Size of a PriorityQueue
The .size() method returns the number of items in a PriorityQueue.
Syntax
priorityqueue.size()
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> food = new PriorityQueue<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");return food;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();System.out.println(food.size());}}
Output:
5
Traversing a PriorityQueue
A PriorityQueue can be traversed with a for-each loop. Items will be returned in the order they were inserted, not in priority order.
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> food = new PriorityQueue<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");return food;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();for (String i : food) {System.out.println(i);}}}
Output:
CabbagePizzaSausagePotatoesSalad
.peek() and .poll() Methods
The .peek() method retrieves the head of the queue without removing it, while .poll() retrieves and removes it.
Syntax
priorityqueue.peek();priorityqueue.poll();
Example
import java.util.PriorityQueue;public class Main {public static PriorityQueue<String> SetupPriorityQueue() {PriorityQueue<String> food = new PriorityQueue<String>();food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");return food;}public static void main(String[] args) {PriorityQueue<String> food = SetupPriorityQueue();System.out.println(food.peek());while (food.size() > 0) {System.out.println(food.poll());}System.out.println(food.peek());}}
Output:
CabbageCabbagePizzaPotatoesSaladSausagenull
Using a Custom Comparator
A custom Comparator can be used to define an alternative priority scheme.
Syntax
import java.util.PriorityQueue;import java.util.Comparator;static class CustomComparator implements Comparator<DataType> {@Overridepublic int compare(DataType item1, DataType item2) {// Return a positive value if item1 < item2, and a negative value if item1 > item2}}PriorityQueue<DataType> q = new PriorityQueue<DataType>(new CustomComparator());
Parameters:
DataType: The data type being compared.
Return value:
Returns a positive value if the first argument comes before the second and a negative value if it comes after.
Example
import java.util.PriorityQueue;import java.util.Comparator;public class Main {static class CustomComparator implements Comparator<String> {@Overridepublic int compare(String item1, String item2) {return item1.compareTo(item2) < 0 ? 1 : -1;}}public static void main(String[] args) {PriorityQueue<String> food = new PriorityQueue<String>(new CustomComparator());food.add("Cabbage");food.add("Pizza");food.add("Sausage");food.add("Potatoes");food.add("Salad");while (food.size() > 0) {System.out.println(food.poll());}}}
Output:
SausageSaladPotatoesPizzaCabbage
Frequently Asked Questions
1. What is the default ordering of elements in a PriorityQueue?
By default, a PriorityQueue uses the natural ordering of its elements. This means:
- For numeric types (e.g.,
Integer), lower numbers have higher priority. - For strings, lexicographical order is used (e.g., “apple” < “banana”).
2. Can a PriorityQueue contain duplicate elements?
Yes, a PriorityQueue allows duplicate elements. However, their relative ordering is determined by the priority rules, not insertion order.
3. Is PriorityQueue thread-safe?
No, PriorityQueue is not thread-safe. For concurrent access, use PriorityBlockingQueue from the java.util.concurrent package.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours