Create a program that uses a priority queue to collect user name and user age fr
ID: 3820634 • Letter: C
Question
Create a program that uses a priority queue to collect user name and user age from a system user and then displays those values in ascending order (regardless of the order in which they are added).
Use jave
import java.util.PriorityQueue;
public class MIKESQCOMPARATORMAIN
{
public static void main(String[] args)
{
MyComparator comparator = new MyComparator();
PriorityQueue<Employee> pQueue = new PriorityQueue<Employee>(7, comparator);
pQueue.offer(new Employee("AAA", 15000));
pQueue.offer(new Employee("BBB", 12000));
pQueue.offer(new Employee("CCC", 7500));
pQueue.offer(new Employee("DDD", 17500));
pQueue.offer(new Employee("EEE", 21500));
pQueue.offer(new Employee("FFF", 29000));
pQueue.offer(new Employee("GGG", 14300));
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
}
}
Explanation / Answer
HI, PLease find my implementation.
I have sorted base on age.
Please let me know in case of any issue.
###############
public class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return name+", "+age;
}
}
######################
import java.util.Comparator;
public class MyComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
if(o1.getAge() > o2.getAge())
return 1;
else if(o1.getAge() < o2.getAge())
return -1;
else
return 0;
}
}
######################
import java.util.PriorityQueue;
public class MIKESQCOMPARATORMAIN
{
public static void main(String[] args)
{
MyComparator comparator = new MyComparator();
PriorityQueue<Employee> pQueue = new PriorityQueue<Employee>(7, comparator);
pQueue.offer(new Employee("AAA", 15000));
pQueue.offer(new Employee("BBB", 12000));
pQueue.offer(new Employee("CCC", 7500));
pQueue.offer(new Employee("DDD", 17500));
pQueue.offer(new Employee("EEE", 21500));
pQueue.offer(new Employee("FFF", 29000));
pQueue.offer(new Employee("GGG", 14300));
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
System.out.println(pQueue.poll());
}
}
/*
Sample run:
CCC, 7500
BBB, 12000
GGG, 14300
AAA, 15000
DDD, 17500
EEE, 21500
FFF, 29000
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.