Problem Statement: Write a Java program to create a PriorityQueue to manage a to-do list with tasks having different priorities.
Here’s a Java program that demonstrates how to create a PriorityQueue
to manage a to-do list with tasks having different priorities.
package com.javacodepoint.collection;
import java.util.PriorityQueue;
class Task implements Comparable<Task> {
private String name;
private int priority;
public Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
@Override
public int compareTo(Task other) {
// Tasks are compared based on their priorities
return Integer.compare(this.priority, other.priority);
}
@Override
public String toString() {
return "[" + name + ", Priority: " + priority + "]";
}
}
public class PriorityQueueToDoList {
public static void main(String[] args) {
PriorityQueue<Task> toDoQueue = new PriorityQueue<>();
// Adding tasks to the to-do list with different priorities
toDoQueue.offer(new Task("Task 1", 3));
toDoQueue.offer(new Task("Task 2", 1));
toDoQueue.offer(new Task("Task 3", 2));
toDoQueue.offer(new Task("Task 4", 4));
toDoQueue.offer(new Task("Task 5", 2));
// Processing tasks in priority order
while (!toDoQueue.isEmpty()) {
Task task = toDoQueue.poll();
System.out.println("Task Completed: " + task);
}
}
}
OUTPUT:
Task Completed: [Task 2, Priority: 1]
Task Completed: [Task 5, Priority: 2]
Task Completed: [Task 3, Priority: 2]
Task Completed: [Task 1, Priority: 3]
Task Completed: [Task 4, Priority: 4]
Explanation:
Task
class: This class represents a task with a name and a priority. It implements theComparable
interface to allow tasks to be compared based on their priorities.- The
compareTo
method is implemented to compare tasks based on their priorities. - The
toString
method is overridden to provide a readable representation of a task.
- The
ToDoList
class: This is the main class that manages the to-do list using aPriorityQueue
of tasks.- In the
main
method, we create aPriorityQueue
namedtoDoQueue
to store tasks. The tasks will automatically be ordered based on their priorities due to the priority queue. - We add tasks to the to-do list using the
offer
method, which adds tasks to the queue while maintaining their order based on priority. - We process tasks in priority order using a
while
loop. We continuouslypoll
tasks from thetoDoQueue
, which removes and returns the task with the highest priority. This allows us to process tasks in order of priority.
- In the
By using a PriorityQueue
, the program effectively manages a to-do list with tasks having different priorities. Tasks are automatically ordered and processed based on their priorities, ensuring that higher-priority tasks are completed first.
See also: Basic Queue Implementation using LinkedList.