Skip to main content

Priority Queue

Priority Queue
  •  Priority queue is an implementation class of queue interface.
  • It stores objects in ascending order based on some priority.
  • It store only homogeneous element which are of comparable type.
  • Constructor of priority queue

— Zero parameter
priorityqueue()

— Comparator object type
priorityqueue(comparator c1)

Java program to implement PriorityQueue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Priorityqueue
{
 
      public static void main(String[] args)
 
        {
            System.out.println("***************************");
 
            PriorityQueue q1=new PriorityQueue<>(2);
 
            q1.add("bhavesh");
            q1.add("hardik");
            q1.add("r ohit");
            q1.add("abhilash");
            q1.add("vivek");
 
          //q1.add(23);
           System.out.println("queue size: "+q1.size());
 
           Object obj2=q1.peek();
 
           System.out.println(q1.size());
 
           Object obj1=q1.poll();
 
           while(obj1!=null)
            {
 
              System.out.println(obj1);
 
              obj1=q1.poll();
 
            }
 
           //after emptying queue output is null
           System.out.println(q1.poll());
 
          System.out.println("***************************");
      }
 
}
 
output:
 
***************************
queue size: 5
5
abhilash
bhavesh
hardik
rohit
vivek
null
***************************