Java Priority Queue of User Defined Objects Example

Java Queue Examples

In this example, you’ll learn how to create a priority queue of user-defined objects.

Since a priority queue needs to compare its elements and order them accordingly, the user-defined class must implement the Comparable interface, or you must provide a Comparator while creating the priority queue. Otherwise, the priority queue will throw a ClassCastException when you add new objects to it.

Java Priority Queue of User Defined Objects Example

Check out the following example in which we create a priority queue of a custom class called Employee. The Employee class implements the Comparable interface and compares two employees by their salary.
import java.util.Objects;
import java.util.PriorityQueue;

class Employee implements Comparable<Employee> {
    private String name;
    private double salary;

    public Employee(String name, double salary) { = name;
        this.salary = salary;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public double getSalary() {
        return salary;

    public void setSalary(double salary) {
        this.salary = salary;

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return, salary) == 0 &&

    public int hashCode() {
        return Objects.hash(name, salary);

    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +

    // Compare two employee objects by their salary
    public int compareTo(Employee employee) {
        if(this.getSalary() > employee.getSalary()) {
            return 1;
        } else if (this.getSalary() < employee.getSalary()) {
            return -1;
        } else {
            return 0;

public class PriorityQueueUserDefinedObjectExample {
    public static void main(String[] args) {

        // Create a PriorityQueue
        PriorityQueue<Employee> employeePriorityQueue = new PriorityQueue<>();

        // Add items to the Priority Queue
        employeePriorityQueue.add(new Employee("Rajeev", 100000.00));
        employeePriorityQueue.add(new Employee("Chris", 145000.00));
        employeePriorityQueue.add(new Employee("Andrea", 115000.00));
        employeePriorityQueue.add(new Employee("Jack", 167000.00));

        while (!employeePriorityQueue.isEmpty()) {


Employee{name='Rajeev', salary=100000.0}
Employee{name='Andrea', salary=115000.0}
Employee{name='Chris', salary=145000.0}
Employee{name='Jack', salary=167000.0}
Notice how the Employee with the lowest salary is removed first.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course