Java Todo App
A Java todo app keeps a list of tasks with priorities and due dates, and lets you add, complete, filter and remove them. Unlike the earlier projects, this one is a real command-line tool: each command runs, updates a save file and exits, just like git or npm. Building it teaches text parsing, java.time date handling, Predicate filters, multi-level sorting and simple file storage.
It follows the Java Bank App. You model a task, parse friendly input such as Pay rent !high @tomorrow, filter and sort the list, save it to a tab-separated file, and finish with todo.jar. All examples were run on JDK 21.
Model a Task With a Record and a Priority Enum
A task has an id, a title, a priority, an optional due date and a done flag. The priority is an enum, so only three values are possible and they sort in declaration order: HIGH, MEDIUM, LOW.
package com.gocourse.todo;
public enum Priority {
HIGH("!!!"), MEDIUM("!! "), LOW("! ");
private final String marker;
Priority(String marker) {
this.marker = marker;
}
public String marker() { return marker; }
/** Accepts "high", "h", "HIGH" and so on. */
public static Priority parse(String text) {
String value = text.toUpperCase();
for (Priority p : values()) {
if (!value.isEmpty() && p.name().startsWith(value)) return p;
}
throw new IllegalArgumentException("Priority must be high, medium or low, not '" + text + "'");
}
}
package com.gocourse.todo;
import java.time.LocalDate;
/** One todo item. "due" may be null when the task has no deadline. */
public record Task(int id, String title, Priority priority, LocalDate due, boolean done) {
public Task {
if (title == null || title.isBlank()) throw new IllegalArgumentException("Title is required");
if (title.contains("\t") || title.contains("\n")) {
throw new IllegalArgumentException("Title cannot contain tabs or line breaks");
}
title = title.strip();
if (priority == null) priority = Priority.MEDIUM;
}
public Task markDone() { return new Task(id, title, priority, due, true); }
public Task markPending() { return new Task(id, title, priority, due, false); }
public boolean isOverdue(LocalDate today) {
return !done && due != null && due.isBefore(today);
}
}
How it works:
duecan benullbecause many tasks, like "Buy milk", have no deadline.isOverduechecks fornullbefore comparing dates.- The compact constructor rejects tabs and line breaks in titles, because the save file uses tabs and new lines as separators. It also gives a missing priority the default
MEDIUM. markDoneandmarkPendingreturn newTaskobjects, the same immutable style used in the Java Student Manager.marker()gives each priority a fixed-width symbol (!!!,!!,!) so the list columns line up.
Parse Todo Input With Priorities and Due Dates
Typing flags like --priority high --due 2026-11-19 is slow. The app accepts short markers anywhere in the text: !high sets the priority and @tomorrow sets the due date.
package com.gocourse.todo;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
/** Turns "Pay rent !high @2026-12-01" into a title, a priority and a due date. */
public class TaskParser {
public record Parsed(String title, Priority priority, LocalDate due) { }
public static Parsed parse(String input, LocalDate today) {
List<String> titleWords = new ArrayList<>();
Priority priority = Priority.MEDIUM;
LocalDate due = null;
for (String word : input.strip().split("\\s+")) {
if (word.startsWith("!") && word.length() > 1) {
priority = Priority.parse(word.substring(1));
} else if (word.startsWith("@") && word.length() > 1) {
due = parseDate(word.substring(1), today);
} else {
titleWords.add(word);
}
}
return new Parsed(String.join(" ", titleWords), priority, due);
}
static LocalDate parseDate(String text, LocalDate today) {
return switch (text.toLowerCase()) {
case "today" -> today;
case "tomorrow" -> today.plusDays(1);
case "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" ->
today.with(TemporalAdjusters.next(DayOfWeek.valueOf(text.toUpperCase()))); // never today
default -> {
try {
yield LocalDate.parse(text); // ISO format: 2026-12-01
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Unknown date '" + text
+ "'. Use YYYY-MM-DD, today, tomorrow or a weekday");
}
}
};
}
}
package com.gocourse.todo;
import java.time.LocalDate;
public class ParserDemo {
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 18); // a Wednesday
String[] inputs = {
"Buy milk",
"Pay electricity bill !high @tomorrow",
"Submit GST return @2026-11-20 !h",
"Team meeting @friday !low",
"Call plumber @someday",
"Fix bug !urgent",
};
for (String input : inputs) {
try {
TaskParser.Parsed p = TaskParser.parse(input, today);
System.out.printf("%-38s -> \"%s\", %s, due %s%n", input, p.title(), p.priority(), p.due());
} catch (IllegalArgumentException e) {
System.out.printf("%-38s -> error: %s%n", input, e.getMessage());
}
}
}
}
Buy milk -> "Buy milk", MEDIUM, due null
Pay electricity bill !high @tomorrow -> "Pay electricity bill", HIGH, due 2026-11-19
Submit GST return @2026-11-20 !h -> "Submit GST return", HIGH, due 2026-11-20
Team meeting @friday !low -> "Team meeting", LOW, due 2026-11-20
Call plumber @someday -> error: Unknown date 'someday'. Use YYYY-MM-DD, today, tomorrow or a weekday
Fix bug !urgent -> error: Priority must be high, medium or low, not 'urgent'
| Marker | Meaning | Example result (today = Wed 18 Nov 2026) |
|---|---|---|
!high, !h | High priority | HIGH |
!low, !l | Low priority | LOW |
@today | Due today | 2026-11-18 |
@tomorrow | Due tomorrow | 2026-11-19 |
@friday | Next Friday | 2026-11-20 |
@2026-12-01 | Exact ISO date | 2026-12-01 |
How it works:
- The input is split into words. Words starting with
!or@are markers; every other word becomes part of the title, so the markers can appear in any order. today.with(TemporalAdjusters.next(DayOfWeek.FRIDAY))jumps to the next Friday. On a Friday it returns the Friday a week later, never the same day.LocalDate.parsereads ISO dates (YYYY-MM-DD) and throwsDateTimeParseExceptionfor anything else. The parser turns that into anIllegalArgumentExceptionwith a helpful message. See Java Date Parsing for other formats.todayis a parameter, notLocalDate.now(), so the parser gives the same results in tests on any day.
Filter and Sort Tasks With Predicate and Comparator
TodoList stores the tasks and returns filtered, sorted views. Filters are Predicate<Task> objects, which can be combined with and, or and negate, as covered in Java Functional Interfaces.
package com.gocourse.todo;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/** All tasks, with methods to change them and to view them filtered and sorted. */
public class TodoList {
/** Pending before done, then HIGH before LOW, then earliest due date (no date last), then id. */
public static final Comparator<Task> DISPLAY_ORDER = Comparator
.comparing(Task::done)
.thenComparing(Task::priority)
.thenComparing(Task::due, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparingInt(Task::id);
private final List<Task> tasks = new ArrayList<>();
private int nextId = 1;
public TodoList(List<Task> loaded) {
for (Task task : loaded) {
tasks.add(task);
nextId = Math.max(nextId, task.id() + 1);
}
}
public Task add(String title, Priority priority, LocalDate due) {
Task task = new Task(nextId, title, priority, due, false);
tasks.add(task);
nextId++;
return task;
}
public Task complete(int id) {
return replace(id, Task::markDone);
}
public Task reopen(int id) {
return replace(id, Task::markPending);
}
public Task remove(int id) {
Task task = find(id);
tasks.remove(task);
return task;
}
/** Deletes all finished tasks and says how many were removed. */
public int clearDone() {
int before = tasks.size();
tasks.removeIf(Task::done);
return before - tasks.size();
}
public List<Task> view(Predicate<Task> filter) {
return tasks.stream().filter(filter).sorted(DISPLAY_ORDER).toList();
}
public List<Task> all() {
return List.copyOf(tasks);
}
private Task replace(int id, UnaryOperator<Task> change) {
Task old = find(id);
Task updated = change.apply(old);
tasks.set(tasks.indexOf(old), updated);
return updated;
}
private Task find(int id) {
return tasks.stream().filter(t -> t.id() == id).findFirst()
.orElseThrow(() -> new IllegalArgumentException("No task #" + id));
}
// ready-made filters
public static Predicate<Task> pending() { return t -> !t.done(); }
public static Predicate<Task> done() { return Task::done; }
public static Predicate<Task> overdue(LocalDate today) { return t -> t.isOverdue(today); }
public static Predicate<Task> dueBy(LocalDate date) {
return t -> !t.done() && t.due() != null && !t.due().isAfter(date);
}
}
package com.gocourse.todo;
import java.time.LocalDate;
import java.util.List;
public class ListDemo {
static void show(String heading, List<Task> tasks) {
System.out.println(heading);
tasks.forEach(t -> System.out.printf(" #%d %s %-22s %s%n",
t.id(), t.done() ? "[x]" : "[ ]", t.title(), t.due() == null ? "-" : t.due()));
}
public static void main(String[] args) {
LocalDate today = LocalDate.of(2026, 11, 18);
TodoList todo = new TodoList(List.of());
todo.add("Buy milk", Priority.LOW, null);
todo.add("Pay electricity bill", Priority.HIGH, LocalDate.of(2026, 11, 19));
todo.add("Renew passport", Priority.HIGH, LocalDate.of(2026, 11, 10));
todo.add("Write blog post", Priority.MEDIUM, LocalDate.of(2026, 11, 25));
todo.add("Book train tickets", Priority.HIGH, null);
todo.complete(1);
show("All (display order):", todo.view(t -> true));
show("Pending:", todo.view(TodoList.pending()));
show("Overdue:", todo.view(TodoList.overdue(today)));
show("Due by tomorrow:", todo.view(TodoList.dueBy(today.plusDays(1))));
show("High priority and pending:", todo.view(TodoList.pending().and(t -> t.priority() == Priority.HIGH)));
System.out.println("Cleared " + todo.clearDone() + " finished task(s), " + todo.all().size() + " left");
}
}
All (display order):
#3 [ ] Renew passport 2026-11-10
#2 [ ] Pay electricity bill 2026-11-19
#5 [ ] Book train tickets -
#4 [ ] Write blog post 2026-11-25
#1 [x] Buy milk -
Pending:
#3 [ ] Renew passport 2026-11-10
#2 [ ] Pay electricity bill 2026-11-19
#5 [ ] Book train tickets -
#4 [ ] Write blog post 2026-11-25
Overdue:
#3 [ ] Renew passport 2026-11-10
Due by tomorrow:
#3 [ ] Renew passport 2026-11-10
#2 [ ] Pay electricity bill 2026-11-19
High priority and pending:
#3 [ ] Renew passport 2026-11-10
#2 [ ] Pay electricity bill 2026-11-19
#5 [ ] Book train tickets -
Cleared 1 finished task(s), 4 left
How it works:
DISPLAY_ORDERsorts by four keys in turn.comparing(Task::done)putsfalse(pending) beforetrue(done). Then enum order putsHIGHfirst. Then the earliest due date wins.Comparator.nullsLast(...)places tasks without a due date after those with one. Without it, comparing anulldate would throwNullPointerException.- "Book train tickets" is
HIGHbut has no date, so it appears after the datedHIGHtasks and before theMEDIUMone. pending().and(t -> t.priority() == Priority.HIGH)combines two filters into one without writing a new method.replacetakes aUnaryOperator<Task>(a function fromTasktoTask), socompleteandreopenshare the same find-and-replace code.
Save the Todo List to a Tab-Separated File
A command-line tool forgets everything when it exits, so every change is saved to a file. Tabs are a better separator than commas here, because task titles often contain commas.
package com.gocourse.todo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/** Stores tasks one per line: id, done, priority, due date, title, separated by tabs. */
public class TodoFileStore {
private final Path file;
public TodoFileStore(Path file) {
this.file = file;
}
public List<Task> load() throws IOException {
if (Files.notExists(file)) return List.of();
List<Task> tasks = new ArrayList<>();
for (String line : Files.readAllLines(file)) {
if (line.isBlank()) continue;
String[] f = line.split("\t", 5); // limit 5: the title is always the last field
LocalDate due = f[3].equals("-") ? null : LocalDate.parse(f[3]);
tasks.add(new Task(Integer.parseInt(f[0]), f[4], Priority.valueOf(f[2]), due, f[1].equals("x")));
}
return tasks;
}
public void save(List<Task> tasks) throws IOException {
List<String> lines = new ArrayList<>();
for (Task t : tasks) {
lines.add(String.join("\t", String.valueOf(t.id()), t.done() ? "x" : "-",
t.priority().name(), t.due() == null ? "-" : t.due().toString(), t.title()));
}
Path temp = file.resolveSibling(file.getFileName() + ".tmp");
Files.write(temp, lines);
Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING);
}
}
package com.gocourse.todo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.List;
public class FileDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("todo-demo.tsv");
TodoFileStore store = new TodoFileStore(file);
TodoList todo = new TodoList(List.of());
todo.add("Buy milk, bread and eggs", Priority.LOW, null);
todo.add("Pay electricity bill", Priority.HIGH, LocalDate.of(2026, 11, 19));
todo.complete(1);
store.save(todo.all());
System.out.println("File contents (tabs shown as ->):");
Files.readAllLines(file).forEach(line -> System.out.println(" " + line.replace("\t", " -> ")));
TodoList reloaded = new TodoList(store.load());
System.out.println("Reloaded: " + reloaded.all());
System.out.println("Next id: " + reloaded.add("New task", null, null).id());
Files.delete(file);
}
}
File contents (tabs shown as ->):
1 -> x -> LOW -> - -> Buy milk, bread and eggs
2 -> - -> HIGH -> 2026-11-19 -> Pay electricity bill
Reloaded: [Task[id=1, title=Buy milk, bread and eggs, priority=LOW, due=null, done=true], Task[id=2, title=Pay electricity bill, priority=HIGH, due=2026-11-19, done=false]]
Next id: 3
How it works:
- Each line holds five fields: id,
xor-for done, priority name, date or-, and the title.-stands for "empty" so no field is ever blank. split("\t", 5)splits into at most five parts. The title is last, so it keeps its commas and spaces exactly.Priority.valueOf("HIGH")turns the saved name back into the enum constant, andLocalDate.parserestores the date.- The
TodoListconstructor setsnextIdpast the highest loaded id, so new tasks never reuse an existing number. - Writing to a
.tmpfile and then moving it replaces the old file in one step, the same safe-save pattern as the student manager.
Build the Java Todo App Command-Line Tool
TodoApp reads the command from args, loads the file, runs the command, saves, and returns an exit code: 0 for success and 1 for a user error. Scripts and other programs can check that code.
package com.gocourse.todo;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/** Command-line todo app: java -jar todo.jar <command> [arguments] */
public class TodoApp {
public static void main(String[] args) {
Path file = Path.of(System.getProperty("todo.file", "todo.tsv"));
LocalDate today = LocalDate.parse(System.getProperty("todo.today", LocalDate.now().toString()));
try {
System.exit(run(args, new TodoFileStore(file), today));
} catch (IOException e) {
System.err.println("Cannot read or write " + file + ": " + e.getMessage());
System.exit(2);
}
}
/** Runs one command and returns the exit code: 0 = success, 1 = user error. */
static int run(String[] args, TodoFileStore store, LocalDate today) throws IOException {
if (args.length == 0) args = new String[] {"list"};
String command = args[0].toLowerCase();
String rest = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
TodoList todo = new TodoList(store.load());
try {
switch (command) {
case "add" -> {
TaskParser.Parsed p = TaskParser.parse(rest, today);
Task task = todo.add(p.title(), p.priority(), p.due());
System.out.println("Added #" + task.id() + ": " + task.title());
}
case "done" -> System.out.println("Completed #" + todo.complete(id(rest)).id());
case "undo" -> System.out.println("Reopened #" + todo.reopen(id(rest)).id());
case "remove" -> System.out.println("Removed: " + todo.remove(id(rest)).title());
case "clear" -> System.out.println("Cleared " + todo.clearDone() + " finished task(s)");
case "list" -> {
print(todo.view(filter(rest, today)), today);
return 0; // nothing changed, no need to save
}
default -> {
System.out.println("Commands: add <text> [!high|!medium|!low] [@date], "
+ "list [all|done|overdue|today], done <id>, undo <id>, remove <id>, clear");
return 1;
}
}
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
return 1;
}
store.save(todo.all());
return 0;
}
private static Predicate<Task> filter(String name, LocalDate today) {
return switch (name.toLowerCase()) {
case "", "pending" -> TodoList.pending();
case "all" -> t -> true;
case "done" -> TodoList.done();
case "overdue" -> TodoList.overdue(today);
case "today" -> TodoList.dueBy(today);
default -> throw new IllegalArgumentException("Unknown list filter: " + name);
};
}
private static int id(String text) {
try {
return Integer.parseInt(text.replace("#", "").strip());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Give a task number, for example: done 3");
}
}
private static void print(List<Task> tasks, LocalDate today) {
if (tasks.isEmpty()) {
System.out.println("Nothing to show.");
return;
}
for (Task t : tasks) {
System.out.printf("%3d. [%s] %s %-28s %s%n", t.id(), t.done() ? "x" : " ",
t.priority().marker(), t.title(), dueText(t, today));
}
}
private static String dueText(Task t, LocalDate today) {
if (t.due() == null) return "";
long days = ChronoUnit.DAYS.between(today, t.due());
String when = days == 0 ? "today" : days == 1 ? "tomorrow"
: days > 0 ? "in " + days + " days" : Math.abs(days) + " days ago";
return t.due() + " (" + when + (t.isOverdue(today) ? ", OVERDUE" : "") + ")";
}
}
How it works:
runis separate frommainand returns anintinstead of callingSystem.exititself. Tests can callrunwith any arguments and check the result without the JVM shutting down.- With no arguments, the app runs
list, the most common command. listreturns beforestore.save(...), so reading the list never rewrites the file.- The file and the date come from system properties (
-Dtodo.file=...and-Dtodo.today=...), with sensible defaults. The second one exists only for repeatable demos and tests. dueTextusesChronoUnit.DAYS.betweento print "tomorrow", "in 12 days" or "8 days ago", which is easier to read than a bare date.
Real-World Example: Manage Your Day With todo.jar
todo-app/
└── src/
└── com/
└── gocourse/
└── todo/
├── Priority.java
├── Task.java
├── TaskParser.java
├── TodoApp.java
├── TodoFileStore.java
└── TodoList.java
cd todo-app
javac -d out src/com/gocourse/todo/*.java
jar --create --file todo.jar --main-class com.gocourse.todo.TodoApp -C out .
# a short command for the terminal (Linux/macOS); the date is fixed for this demo
alias todo='java -Dtodo.today=2026-11-18 -jar todo.jar'
A session on Wednesday, 18 November 2026. ! is quoted in the terminal because some shells treat it as a special character.
$ todo add Pay electricity bill '!high' @tomorrow
Added #1: Pay electricity bill
$ todo add Renew passport '!h' @2026-11-10
Added #2: Renew passport
$ todo add Write Java records post @friday
Added #3: Write Java records post
$ todo add Buy milk '!low'
Added #4: Buy milk
$ todo add Submit GST return '!high' @2026-11-30
Added #5: Submit GST return
$ todo add Call plumber @someday
Error: Unknown date 'someday'. Use YYYY-MM-DD, today, tomorrow or a weekday
$ echo $?
1
$ todo list
2. [ ] !!! Renew passport 2026-11-10 (8 days ago, OVERDUE)
1. [ ] !!! Pay electricity bill 2026-11-19 (tomorrow)
5. [ ] !!! Submit GST return 2026-11-30 (in 12 days)
3. [ ] !! Write Java records post 2026-11-20 (in 2 days)
4. [ ] ! Buy milk
$ todo done 4
Completed #4
$ todo done 9
Error: No task #9
$ todo list overdue
2. [ ] !!! Renew passport 2026-11-10 (8 days ago, OVERDUE)
$ todo list all
2. [ ] !!! Renew passport 2026-11-10 (8 days ago, OVERDUE)
1. [ ] !!! Pay electricity bill 2026-11-19 (tomorrow)
5. [ ] !!! Submit GST return 2026-11-30 (in 12 days)
3. [ ] !! Write Java records post 2026-11-20 (in 2 days)
4. [x] ! Buy milk
$ todo clear
Cleared 1 finished task(s)
$ todo remove #3
Removed: Write Java records post
$ todo
2. [ ] !!! Renew passport 2026-11-10 (8 days ago, OVERDUE)
1. [ ] !!! Pay electricity bill 2026-11-19 (tomorrow)
5. [ ] !!! Submit GST return 2026-11-30 (in 12 days)
The file todo.tsv after the session (tabs between fields):
1 - HIGH 2026-11-19 Pay electricity bill
2 - HIGH 2026-11-10 Renew passport
5 - HIGH 2026-11-30 Submit GST return
How it works:
- Natural input.
@fridaybecame 20 November and!hbecameHIGH, while the rest of each line became the title. - Smart ordering. The overdue passport task is at the top, followed by the other
HIGHtasks by date, thenMEDIUM, thenLOW. The finished task moves to the bottom inlist all. - Clear errors with exit codes. An unknown date and a missing task print a message and return exit code
1, so a script can detect the failure with$?. - Persistent state. Every command loaded
todo.tsv, changed it and saved it. Removed and cleared tasks are gone from the file, and the ids of the remaining tasks never change. - Read-only listing.
todowith no arguments shows pending tasks and does not rewrite the file.
The next project, the Java File Manager, builds on this command-line style to list, copy, move and search files with the NIO Files API.