Skip to content

What is Java Priority Queue with real time application example?

Java priority queue with example and implementation will be answered. With real time application example program, the priority queue in java will be described.

Answer:

What is Priority Queue in Java?

Priority queue is just like a traditional queue with difference that when a high priority elements come to join a queue, it gets added at the head of the queue instead of tail (We know that in a queue, elements get added at the tail).

For example, let’s say, 5 elements with the same priority are in a queue. If another element with same priority comes then it will be added at tail of the queue. But, if some element comes with high priority then it will be added at the head of the queue. That’s it. This is the properties of a priority queue.

Though there are many uses of priority queue, one simple use we can consider that is thread scheduling algorithms where high priority threads start first. You can read thread priority in java. Let’s implement a simple real-time application of priority queue in java

Real time application example of priority queue in java:

Application – Patient Priority queue in a hospital: There is a queue of patients in hospital. It servers normal and emergency case. If some emergency patient come, he will be given a priority and will be treated first.

Solution: To implement it, we will use java PriorityQueue class and java comparator interface. Its Implementation is very simple and code comments has been provided. In program, below classes are implemented.

Class Patient: Patient class having patient name and priority
Class PatientPriorityComparator : Priorityqueue comparator to decide  the emergency patient
Class PriorityQueueExample – Test program for Priority queue, add and remove patient on run time and will manage priority queue.

 

Priority Queue Java implementation- Complete program:

This program adds the patient information at run time and display the patient list. Program allows you to enter information at run time. It gives three options i.e. option 1 – in which you can enter patent name and priority. Option:2 you can display the list of priority queue. Option :3- exit. After implementation test case examples, has been provided.

Patient class

//Patient class having patient name and priority
public class Patient {

	private int patientPriority;
	private String patientName;
	private int patientId;
	
	public Patient(int id,String name,int priority ){		
		this.patientName=name;
		this.patientPriority=priority;
		this.patientId = id;
	}

	public int getPriority() {
		
		return patientPriority;
	}

public int getId() {
		
		return patientId;
	}
	public String getName() {
		
		return patientName;
	}
}


Comparator implementation for priorityqueue

//Priority queue comparator to decide the 
//emergency patient
import java.util.Comparator;

public class PatientPriorityComparator implements Comparator {

	@Override
	public int compare(Patient patient, Patient priorityPatient) {

		// comparison code for Patients on the basis of emergency
		Patient p1 = (Patient) patient;
		Patient p2 = (Patient) priorityPatient;	
		//1 dscending
		//-1		asscending
		

		 if (p1.getPriority() < p2.getPriority()) return 1; if (p1.getPriority() > p2.getPriority())
		        return -1;
		    else { if (p1.getId() <(p2.getId())) return -1; if (p1.getId() > (p2.getId()))
		        return 1;
		    }
		    return 0; 
	
	}	
}

Priorityqueue java example – test program

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

//Test program for Priority queue
//Add and remove patient on run time and will
//manage priority queue.
public class PriorityQueueExample {

	public static void main(String[] args) {

		// Priority
		// NORMAL 1
		// Emergency 2

		boolean exit = false;

		String pName;
		int pPriority;
		int pId;
		//Create Patient priority comparator, so, 
		//priorityQueue class can decide
		//whom to put on head of the list.
		Comparator queueComparator = new PatientPriorityComparator();
		
		//Create a priory queue and assign a comparator to its constructor.
		//Set the initial capacity of the queue to 10 or something.
		PriorityQueue priorityQueue = new PriorityQueue(10,
				queueComparator);

		do {
			//Display options for input data, display list
			// and exit application
			System.out.println("1.Input");
			System.out.println("2.Display list");
			System.out.println("3.Exit");
			
			//Read option from console
			Scanner option = new Scanner(System.in);
			System.out.println("enter your choice");
			int num = option.nextInt();
			
			switch (num) {
			case 1:
				//Enter patient name and priority
				Scanner input = new Scanner(System.in);
				System.out.println("Enter Patient ID:");
				pId = (input.nextInt());
				input.nextLine();
				System.out.println("Enter Patient name:");
				pName = input.nextLine();
				System.out.println("Enter priority:");
				pPriority = (input.nextInt());

				Patient obj = new Patient(pId,pName, pPriority);
				priorityQueue.add(obj);
				break;

			case 2:
				//Display patients list1
				
				while (priorityQueue.size() != 0) {
					//poll () method will display the list 
					// and remove head element from the list.
					System.out.println("Patient\t"
							+ priorityQueue.poll().getName());
				}
				break;

			case 3:
				exit = true;
				break;
			}
		} while (!exit);

	}

}

TEST CASE:

Input:

Following patients are coming with priority 1 or 2(high) and they will be server in first come first serve basis but high priority patient will be treated first.

First, Steave with priority 1 comes
Then John with priority 1
Then Tom with priority 2( higher priority)
Then Peter with priority 1

Output: Treatment should be in order
Tom
Steave
John
Peter

Execution Result:

1.Input
2.Display list
3.Exit
enter your choice
1
Enter Patient ID:
100
Enter Patient name:
Steave
Enter priority:
1
1.Input
2.Display list
3.Exit
enter your choice
1
Enter Patient ID:
101
Enter Patient name:
John
Enter priority:
1
1.Input
2.Display list
3.Exit
enter your choice
1
Enter Patient ID:
102
Enter Patient name:
Tom
Enter priority:
2
1.Input
2.Display list
3.Exit
enter your choice
1
Enter Patient ID:
103
Enter Patient name:
Peter
Enter priority:
1
1.Input
2.Display list
3.Exit
enter your choice
2
Patient      Tom
Patient      Steave
Patient      John
Patient      Peter

1.Input
2.Display list
3.Exit
enter your choice
3


Published inJava Collections