-
Notifications
You must be signed in to change notification settings - Fork 0
Priority Queues
apdjz edited this page Oct 19, 2017
·
1 revision
//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;
}
} //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;
}
}
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);
}
}