Is lesson me hum seekhenge:
- Priority Queue kya hota hai
- Kaise kaam karta hai (Heap concept)
- Default behavior (Min-Heap)
- Custom comparator ke saath use
- Important methods aur examples
Priority Queue ek queue hai jisme:
elements priority ke basis par process hote hain
FIFO (First In First Out) follow nahi karta.
Class:
java.util.PriorityQueuePriorityQueue internally use karta hai:
Heap (Binary Heap)
Default:
Min Heap
Matlab:
smallest element pehle niklega
import java.util.*;
class Test {
public static void main(String[] args){
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(20);
System.out.println(pq);
while(!pq.isEmpty()){
System.out.println(pq.poll());
}
}
}Output:
10
20
30
| Method | Use |
|---|---|
| add() | insert element |
| offer() | insert (safe) |
| peek() | top element |
| poll() | remove top |
| remove() | delete |
Default:
Min Heap → smallest first
Max Heap banane ke liye:
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
pq.add(10);
pq.add(30);
pq.add(20);
while(!pq.isEmpty()){
System.out.println(pq.poll());
}Output:
30
20
10
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);class Student {
int marks;
Student(int marks){
this.marks = marks;
}
}Use:
PriorityQueue<Student> pq = new PriorityQueue<>(
(s1, s2) -> s2.marks - s1.marks
);
pq.add(new Student(80));
pq.add(new Student(90));
pq.add(new Student(70));
while(!pq.isEmpty()){
System.out.println(pq.poll().marks);
}✔ elements sorted nahi dikhte
✔ head element highest priority hota hai
✔ duplicate allowed
Dijkstra Algorithm
CPU Scheduling
Task Scheduling
Top K elements problems
| Feature | Queue | PriorityQueue |
|---|---|---|
| Order | FIFO | Priority based |
| Structure | Linear | Heap |
✔ PriorityQueue thread-safe nahi hota
✔ null values allow nahi
✔ internal structure heap hota hai
- PriorityQueue ka internal structure kya hai?
- Min heap aur max heap me difference?
- PriorityQueue me sorting kaise hoti hai?
- Custom comparator ka use kaise karte hain?
Is lesson me humne seekha:
✔ Priority Queue concept
✔ Heap working (Min/Max)
✔ Important methods
✔ Custom comparator
✔ Real-life usage
PriorityQueue Java me priority-based data processing ke liye use hota hai aur algorithms me bahut powerful hota hai.