In Java, a PriorityQueue orders elements based on priority rather than insertion order. By using a Comparator, we can define custom ordering logic, override natural ordering, and prioritize elements or objects based on specific requirements.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Creating PriorityQueue with Comparator (max-heap)
PriorityQueue<Integer> pq
= new PriorityQueue<>((a, b) -> b - a);
pq.add(10);
pq.add(30);
pq.add(20);
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
}
}
Output
30 20 10
Explanation
- A Comparator is used to reverse the natural ordering.
- Higher values get higher priority.
- poll() removes elements based on the defined priority.
Syntax
PriorityQueue<Type> pq = new PriorityQueue<>(Comparator);
- Parameters: "comparator" defines custom order; if null, natural order is used
Example : PriorityQueue of Objects Using Comparator
import java.util.*;
class Student {
int marks;
String name;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}
public class GFG {
public static void main(String[] args) {
PriorityQueue<Student> pq = new PriorityQueue<>(
(s1, s2) -> s2.marks - s1.marks
);
pq.add(new Student("Aman", 85));
pq.add(new Student("Riya", 92));
pq.add(new Student("Karan", 78));
while (!pq.isEmpty()) {
Student s = pq.poll();
System.out.println(s.name + " " + s.marks);
}
}
}
Output
Riya 92 Aman 85 Karan 78
Explanation
- The Comparator prioritizes students based on marks.
- Students with higher marks are removed first.