VOOZH about

URL: https://www.geeksforgeeks.org/java/implement-priorityqueue-comparator-java/

⇱ Implement PriorityQueue through Comparator in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement PriorityQueue through Comparator in Java

Last Updated : 24 Jan, 2026

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.


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


Output
Riya 92
Aman 85
Karan 78

Explanation

  • The Comparator prioritizes students based on marks.
  • Students with higher marks are removed first.

Related Topics

Comment
Article Tags: