Last Updated:

Java Priority Queue Example

Java Priority Queue

FIFO (First IFirst Out - "first come - first gone"), but sometimes there is a need to process objects in a queue based on priority. For example, we have an application that generates reports and processes a large amount of data that requires a lot of time to process. When customers send requests to our application, a queue is formed, but we want to process premium customers first, and ordinary customers after them. This is where we'll be best off using PriorityQueue.

Briefly about PriorityQueue

  • The class was introduced in Java 1.5 and is part of the Java Collections Framework. PriorityQueue is an unlimited queue. Items are arranged by default in a natural order or sorted using a comparator. PriorityQueue
  • PriorityQueue does not allow you to add -values and objects. The size of the PriorityQueue is unlimited, but we can specify the initial size at the time of its creation. When we add items to a priority queue, its size increases automatically.nullnon-comparable
  • PriorityQueue is not sweatproof! For this purpose, Java implements a class that implements the BlockingQueue interface. It is used in a multithreaded environment.PriorityBlockingQueue, 
  • In addition/removal of elements occurs in time .PriorityQueueO(log(n))

Example of using PriorityQueue in Java

Let's look at the PriorityQueue implementation for the natural order of adding elements, as well as an example of PriorityQueue with a comparator:

First of all, let's create the Customer

We will use random number generation to generate random client objects. For the natural order of adding elements, we will use Integer, which in Java is a wrapper class.

Here's the final code that shows how to use the .PriorityQueue

Note that we use an anonymous class to implement the comparator interface and create a comparator based on ids.

The result of the program will be as follows:

That's all you need to know about If you liked this article, please share with your friends or leave a comment.PriorityQueue.

Want to learn more about memory in Java? Then here's an interesting article about what Heap and Stack memory are in Java.