Java Priority Queue Real-World Example

In this source code example, you’ll learn how to use a Java Priority Queue in real-world projects.

PriorityQueue is a Queue data structure implementation in which objects are processed based on their priority. It's part of the Java Collections Framework and is present in the java.util package.

Real-World Example: Employee Management Based on Priority

import java.util.PriorityQueue;
import java.util.Comparator;

class Employee {
    String name;
    int priority;

    Employee(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }

    @Override
    public String toString() {
        return name + " (Priority: " + priority + ")";
    }
}

public class EmployeeManagement {
    public static void main(String[] args) {
        // Creating a priority queue with custom comparator to manage employees based on their priority
        PriorityQueue<Employee> queue = new PriorityQueue<>(Comparator.comparingInt(emp -> emp.priority));

        // Adding employees to the queue
        queue.add(new Employee("Alice", 3));
        queue.add(new Employee("Bob", 1));
        queue.add(new Employee("Charlie", 2));
        queue.add(new Employee("David", 4));

        // Displaying and processing employees based on priority
        while(!queue.isEmpty()) {
            System.out.println("Processing: " + queue.poll());
        }
    }
}

Output:

Processing: Bob (Priority: 1)
Processing: Charlie (Priority: 2)
Processing: Alice (Priority: 3)
Processing: David (Priority: 4)

Explanation:

1. An Employee class is created with attributes name and priority. The toString method is overridden to represent the employee in a readable format.

2. The main class, EmployeeManagement, creates a PriorityQueue to manage employees based on their priority.

3. Employees are added to the PriorityQueue. The custom comparator ensures that employees with a lower priority value are processed first.

4. The employees are polled (removed and returned) from the queue and displayed, in order of their priority.


Comments