Computer >> Computer tutorials >  >> Programming >> Java

Implement PriorityQueue through Comparator in Java


To implement PriorityQueue through Comparator in Java, the code is as follows −

Example

import java.util.*;
public class Demo{
   public static void main(String[] args){
      Scanner my_scan = new Scanner(System.in);
      PriorityQueue<Demo_class> my_pq = new PriorityQueue<Demo_class>(3, new demoComparator());
      Demo_class obj_1 = new Demo_class("Joe", 25);
      my_pq.add(obj_1);
      Demo_class obj_2 = new Demo_class("Goldberg", 27);
      my_pq.add(obj_2);
      while (!my_pq.isEmpty()){
         System.out.println(my_pq.poll().getName());
      }
   }
}
class demoComparator implements Comparator<Demo_class>{
   public int compare(Demo_class s1, Demo_class s2){
      if (s1.age < s2.age)
      return 1;
      else if (s1.age > s2.age)
      return -1;
      return 0;
   }
}
class Demo_class{
   public String name;
   public int age;
   public Demo_class(String name, int age){
      this.name = name;
      this.age = age;
   }
   public String getName(){
      return name;
   }
}

Output

Goldberg
Joe

A class named Demo contains the main function. Here, a new scanner object and a priority queue are defined. Two instances of the Demo class are created and elements are added to it.

The priority queue is checked whether it is empty, and if not, the poll function is called on the priority queue and its name is obtained. Now, the Comparator is implemented by a newly created class and the compare function compares two values from the two instances of Demo class. The Demo class takes in the name and the age. It defines a constructor and a function named ‘getName’ that returns the name.