Implement PriorityQueue through Comparator in Java

JavaObject Oriented ProgrammingProgramming

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


 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      Scanner my_scan = new Scanner(;
      PriorityQueue<Demo_class> my_pq = new PriorityQueue<Demo_class>(3, new demoComparator());
      Demo_class obj_1 = new Demo_class("Joe", 25);
      Demo_class obj_2 = new Demo_class("Goldberg", 27);
      while (!my_pq.isEmpty()){
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){ = name;
      this.age = age;
   public String getName(){
      return name;



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.

Updated on 04-Jul-2020 08:57:33