Question 7
Back to Exercise
Write Task (title, priority, done) and TodoList classes: add tasks, mark one done by title, and print pending tasks sorted by priority.
Solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Task {
String title;
int priority; // 1 = highest
boolean done;
Task(String title, int priority) { this.title = title; this.priority = priority; }
@Override public String toString() { return "P" + priority + " " + title; }
}
class TodoList {
private final List<Task> tasks = new ArrayList<>();
void add(String title, int priority) { tasks.add(new Task(title, priority)); }
boolean complete(String title) {
for (Task t : tasks) if (t.title.equalsIgnoreCase(title) && !t.done) { t.done = true; return true; }
return false;
}
List<Task> pending() {
List<Task> out = new ArrayList<>();
for (Task t : tasks) if (!t.done) out.add(t);
out.sort(Comparator.comparingInt((Task t) -> t.priority).thenComparing(t -> t.title));
return out;
}
}
public class Main {
public static void main(String[] args) {
TodoList todo = new TodoList();
todo.add("Pay electricity bill", 1);
todo.add("Revise Java OOP", 2);
todo.add("Buy groceries", 3);
todo.add("Apply for internship", 1);
System.out.println(todo.complete("pay electricity bill") + " " + todo.complete("Go jogging"));
for (Task t : todo.pending()) System.out.println(t);
}
}
true false P1 Apply for internship P2 Revise Java OOP P3 Buy groceries
The list owns its Task objects; pending() returns a new sorted list without changing the original order.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!