AI Hints
Home›Java Tutorial›Project: Saving Tasks, Loading Tasks and Reports with Streams
Java · Lesson 117 of 120

Project: Reports with Streams

Useful summaries.

⏱ 2 min read▶ Video at 2:28:28🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Now our tasks can be saved and loaded. Let's use streams to answer useful questions about them.

  • Saved and loaded
  • Ask questions
  • With streams

Task reports

Filter, with task colon colon done, keeps the finished tasks, and count counts them. The next stream finds open tasks with top priority. Grouping by counts the tasks at each priority level. And the last stream finds the first open task alphabetically. Run it. Two of five are done. Pay rent, and finish report, are urgent. There are one, two, and two tasks at each level. And book dentist comes first.

Main.javajava
import java.util.*;
import java.util.stream.*;
public class Main {
    public static void main(String[] args) throws Exception {
        TaskList list = new TaskList();
        new TaskStore("tasks.txt").load().forEach(list::restore);
        List<Task> all = list.all();
        long done = all.stream().filter(Task::done).count();
        System.out.println("Done " + done + " of " + all.size());
        System.out.println("Urgent and open:");
        all.stream().filter(t -> !t.done() && t.priority() == 3)
                    .forEach(t -> System.out.println("  " + t.title()));
        Map<Integer, Long> byPrio = all.stream()
            .collect(Collectors.groupingBy(Task::priority, Collectors.counting()));
        System.out.println("By priority: " + byPrio);
        all.stream().filter(t -> !t.done()).map(Task::title).sorted()
           .findFirst().ifPresent(t -> System.out.println("First open, A-Z: " + t));
    }
}
Output
Done 2 of 5
Urgent and open:
  Pay rent
  Finish report
By priority: {1=1, 2=2, 3=2}
First open, A-Z: Book dentist; maybe Friday
Also uses Task.java
public record Task(int id, String title, int priority, boolean done) {
    public Task {
        if (title.isBlank()) throw new IllegalArgumentException("Title can't be empty");
        if (priority < 1 || priority > 3) throw new IllegalArgumentException("1-3 only");
    }

    public Task complete() {
        return new Task(id, title, priority, true);
    }

    @Override
    public String toString() {
        String box = done ? "[x]" : "[ ]";
        return String.format("%2d %s %-3s %s", id, box, "!".repeat(priority), title);
    }
}
Also uses TaskList.java
import java.util.*;
public class TaskList {
    private final List<Task> tasks = new ArrayList<>();
    private int nextId = 1;

    public Task add(String title, int priority) {
        Task t = new Task(nextId++, title, priority, false);
        tasks.add(t);
        return t;
    }
    public void complete(int id) {
        tasks.replaceAll(t -> t.id() == id ? t.complete() : t);
    }
    public boolean remove(int id) { return tasks.removeIf(t -> t.id() == id); }
    public List<Task> all() { return List.copyOf(tasks); }
    public void restore(Task t) { tasks.add(t); nextId = Math.max(nextId, t.id() + 1); }
}
Also uses TaskStore.java
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class TaskStore {
    private final Path file;
    public TaskStore(String name) { file = Path.of(name); }

    public void save(List<Task> tasks) throws IOException {
        List<String> lines = new ArrayList<>();
        for (Task t : tasks) {
            lines.add(t.id() + ";" + t.priority() + ";" + t.done() + ";" + t.title());
        }
        Files.write(file, lines);
    }

    public List<Task> load() throws IOException {
        List<Task> out = new ArrayList<>();
        if (!Files.exists(file)) return out;
        for (String line : Files.readAllLines(file)) {
            String[] p = line.split(";", 4);
            int id = Integer.parseInt(p[0]), prio = Integer.parseInt(p[1]);
            out.add(new Task(id, p[3], prio, Boolean.parseBoolean(p[2])));
        }
        return out;
    }
}
Also uses tasks.txt
1;3;false;Pay rent
2;1;true;Water plants
3;2;false;Book dentist; maybe Friday
4;2;true;Email Sam
5;3;false;Finish report

Streams on your own data

Once your data is in a list, streams make questions short. Count, filter, group, sort, and find. These five lines would be thirty lines of loops.

keyvalue
How many done?filter + count
Which are urgent?filter + forEach
Per priority?groupingBy + counting
First A-Z?sorted + findFirst

Summary

Streams turn questions about our tasks into short, readable code. Next, the menu that ties everything together.

Key takeaways
  • filter + count
  • groupingBy
  • findFirst
Next up: Project: The Menu — talk to the user