Priority Queue in Java

Posted on April 3, 2012


'Priority Queue' is a data structure similar to Queue, but pulls/pops out the first element with top priority first (FPIFO, for convenience), whereas Queue is just 'First In First Out' (FIFO). This data structure can be used in a variety of applications like Scheduling, Bandwidth Management, Discrete Event Simulation, etc.

I was just coding for fun and for brushing up my skills on algorithms and coded a few examples, as listed below. As shown in the examples, I used the Java's PriorityQueue implementation in the util package.

In the below example, the priority queue is fed with Integer numbers and the priority is determined by checking if the number is a least prime or not.


The output for the above example is:
2 <-- 3 <-- 5 <-- 7 <-- 1 <-- 4 <-- 6 <-- 8 <-- 9 <-- 10 <--
As you see, prime numbers appear before other numbers.

The below example is more of a real world example, where the order of patients to be treated by a doctor can be determined by checking if it's a emergency case or not.

Below is the code for 'Patient' class:

And below is the code for testing Patient priority queue:


The output for the above example is:
Doctor's waiting for patients : Patient3 <-- Patient5 <-- Patient1 <-- Patient2 <-- Patient4 <--
As you see, patients who need to be treated immediately (emergency cases) appear before other patients.

Blog Categories
Disclaimer
The views expressed on this blog are my personal views and do not reflect the views of my employer or campaigns I am supporting.

All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.

All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.