Skip to content

Expense Ledger

The Course
•
20 min study

Build a complete application from this week's boundaries. The expense ledger imports validated values atomically, treats identical retries as replays, rejects conflicting IDs, calculates exact totals and exports canonical text. It stays small enough to trace across every source file.

Understand the contract

Read the application as a flow: raw text enters Ledger.importText; ExpenseParser checks a three-field format; Expense normalizes and validates one value; the ledger stages entries in a private map; and Accepted or Rejected describes the outcome. Reports read committed state only. Main supplies a scenario and displays results rather than implementing storage policy.

The input format is id;category;amount. Categories are FOOD, TRAVEL or OTHER, case-sensitive. Amount text uses plain digits and optionally one or two decimal places; exponent notation and currency signs reject. Positive amounts up to 1000000.00 are accepted and stored at scale two. IDs are trimmed, at most 24 characters, and contain no delimiter or newline. All amounts use one unspecified currency.

Limits are 12000 UTF-16 characters per input, 100 physical lines, 120 characters per line, and 100 distinct stored expenses. Blank lines count toward the line limit and are otherwise skipped. These limits keep practice bounded and ensure any full ledger export can be imported into an empty ledger. This is an in-memory single-threaded model, not a payment system or a durable database.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        Expense first = new Expense("A", new BigDecimal("2.00"));
        Expense replay = new Expense("A", new BigDecimal("2.00"));
        Expense conflict = new Expense("A", new BigDecimal("3.00"));
        System.out.println(first.equals(replay));
        System.out.println(first.equals(conflict));
    }
}

record Expense(String id, BigDecimal amount) {}
Check your prediction
Text
true
false

Trace a different case

The miniature record above assumes normalized amounts. The real Expense constructor enforces that rule, so 2.0 and 2.00 become the same stored value. A conflict is about a stable ID carrying different normalized content. Different IDs with equal amounts are two distinct expenses and both contribute to the total.

Compare the boundary case Java
import java.util.Map;
import java.util.LinkedHashMap;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        Map<String, BigDecimal> entries = new LinkedHashMap<>();
        entries.put("A", new BigDecimal("2.00"));
        entries.put("B", new BigDecimal("2.00"));
        System.out.println(entries.size());
        System.out.println(entries.values().stream().reduce(new BigDecimal("0.00"), BigDecimal::add));
    }
}
Check your prediction
Text
2
4.00

Read the source in layers

SourceResponsibility
Category / ExpenseRepresent and validate one normalized immutable value
ExpenseParserConvert a bounded, unquoted line into Expense
ProblemKeep a physical line number and a useful message; 0 means a whole-input problem
ImportOutcome / Accepted / RejectedMake successful counts and rejected problems separate cases
LedgerOwn state, stage imports, commit once, derive reports and export
Main / LedgerTestDemonstrate behavior / verify its promises

The capstone uses a few library operations in combination. Comparator.comparing(Expense::amount) is the object-key counterpart of intermediate's comparingInt: it extracts a BigDecimal key and uses that key's compareTo, preserving numerical ordering. thenComparing(Expense::id) extracts a String key for ties. entries.values() gives the map's values; copying them into a list prevents a caller from editing map membership through a view.

Start with Expense, then ExpenseParser, the outcome records and Ledger. Only then read Main. Comparator.comparing(Expense::amount) uses BigDecimal's numerical order; the ID tie-breaker makes equal-amount reports deterministic. find expects an exact stored ID: it does not trim lookup arguments. Normalization belongs to construction and import. A missing lookup returns Optional.empty.

A rejected batch collects line problems but publishes none of its candidate entries. An identical repeated row within the batch counts as a replay after its first staged insertion. No account, network or disk operation occurs. Every Run starts with new objects and a fresh ledger.

Run the complete project

Run the expense ledger Java
public record Accepted(int inserted, int replayed) implements ImportOutcome { public Accepted { if (inserted < 0 || replayed < 0) { throw new IllegalArgumentException("negative count"); } } } public enum Category { FOOD, TRAVEL, OTHER } import java.math.BigDecimal; import java.math.RoundingMode; /** One currency; immutable, normalized values make exact replay comparison meaningful. */ public record Expense(String id, Category category, BigDecimal amount) { public Expense { if (id == null || id.trim().isEmpty()) { throw new IllegalArgumentException("id required"); } id = id.trim(); if (id.length() > 24 || id.contains(";") || id.contains("\n") || id.contains("\r")) { throw new IllegalArgumentException("invalid id"); } if (category == null || amount == null) { throw new IllegalArgumentException("category and amount required"); } if (amount.signum() <= 0 || amount.compareTo(new BigDecimal("1000000.00")) > 0) { throw new IllegalArgumentException("amount outside 0.01..1000000.00"); } try { amount = amount.setScale(2, RoundingMode.UNNECESSARY); } catch (ArithmeticException error) { throw new IllegalArgumentException("amount needs at most two decimal places", error); } } } import java.math.BigDecimal; /** Small unquoted format: id;category;amount. Categories are case-sensitive. */ public final class ExpenseParser { public Expense parse(String line) { if (line == null || line.length() > 120) { throw new IllegalArgumentException("line missing or longer than 120 characters"); } String[] fields = line.split(";", -1); if (fields.length != 3) { throw new IllegalArgumentException("expected id;category;amount"); } String decimal = fields[2].trim(); // Reject exponents and unbounded scale before BigDecimal construction. if (!decimal.matches("[0-9]{1,7}(\\.[0-9]{1,2})?")) { throw new IllegalArgumentException("amount needs digits and up to two decimal places"); } Category category; try { category = Category.valueOf(fields[1].trim()); } catch (IllegalArgumentException error) { throw new IllegalArgumentException("category must be FOOD, TRAVEL or OTHER", error); } return new Expense(fields[0], category, new BigDecimal(decimal)); } } public sealed interface ImportOutcome permits Accepted, Rejected {} import java.io.BufferedReader; import java.io.StringReader; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** Single-threaded, in-memory atomic imports; no persistence or concurrent guarantee. */ public final class Ledger { private Map<String, Expense> entries = new LinkedHashMap<>(); private final ExpenseParser parser; public Ledger(ExpenseParser parser) { if (parser == null) { throw new IllegalArgumentException("parser required"); } this.parser = parser; } public ImportOutcome importText(String text) { if (text == null || text.length() > 12000) { return new Rejected(List.of(new Problem(0, "input missing or longer than 12000 characters"))); } Map<String, Expense> candidate = new LinkedHashMap<>(entries); List<Problem> problems = new ArrayList<>(); int inserted = 0; int replayed = 0; int lineNumber = 0; try (BufferedReader reader = new BufferedReader(new StringReader(text))) { String line = reader.readLine(); while (line != null) { lineNumber++; if (lineNumber > 100) { problems.add(new Problem(lineNumber, "more than 100 physical lines")); break; } // Even whitespace-only lines must obey the per-line size limit. if (line.length() > 120) { problems.add(new Problem(lineNumber, "line longer than 120 characters")); } else if (!line.trim().isEmpty()) { try { Expense incoming = parser.parse(line); Expense old = candidate.get(incoming.id()); if (old == null) { candidate.put(incoming.id(), incoming); inserted++; } else if (old.equals(incoming)) { replayed++; } else { problems.add(new Problem(lineNumber, "conflicting id: " + incoming.id())); } } catch (IllegalArgumentException error) { problems.add(new Problem(lineNumber, error.getMessage())); } } line = reader.readLine(); } } catch (IOException error) { throw new IllegalStateException("in-memory read failed", error); } if (candidate.size() > 100) { problems.add(new Problem(0, "ledger capacity is 100 expenses")); } if (!problems.isEmpty()) { return new Rejected(problems); } // This assignment is the only commit point. entries = candidate; return new Accepted(inserted, replayed); } public Optional<Expense> find(String id) { return Optional.ofNullable(entries.get(id)); } public List<Expense> snapshot() { return List.copyOf(entries.values()); } public BigDecimal total() { return entries.values().stream() .map(Expense::amount) .reduce(new BigDecimal("0.00"), BigDecimal::add); } public List<Expense> largestFirst() { Comparator<Expense> byAmount = Comparator.comparing(Expense::amount); return entries.values().stream() .sorted(byAmount.reversed().thenComparing(Expense::id)) .toList(); } public String exportText() { List<Expense> ordered = new ArrayList<>(entries.values()); ordered.sort(Comparator.comparing(Expense::id)); StringBuilder result = new StringBuilder(); for (Expense expense : ordered) { result.append(expense.id()).append(';') .append(expense.category()).append(';') .append(expense.amount().toPlainString()).append('\n'); } return result.toString(); } } public class Main { public static void main(String[] args) { Ledger ledger = new Ledger(new ExpenseParser()); String text = "B;TRAVEL;12.50\nA;FOOD;3.25\n"; System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText("C;OTHER;2.00\nA;FOOD;9.00"))); System.out.println("Total: " + ledger.total().toPlainString()); System.out.print(ledger.exportText()); } static String describe(ImportOutcome outcome) { return switch (outcome) { case Accepted accepted -> "Inserted: " + accepted.inserted() + ", replayed: " + accepted.replayed(); case Rejected rejected -> "Rejected: " + rejected.problems().size() + " problem(s)"; }; } } /** Line 0 means a whole-input limit or missing-input problem. */ public record Problem(int line, String message) { public Problem { if (line < 0 || message == null || message.isEmpty()) { throw new IllegalArgumentException("valid problem required"); } } } import java.util.List; public record Rejected(List<Problem> problems) implements ImportOutcome { public Rejected { problems = List.copyOf(problems); if (problems.isEmpty()) { throw new IllegalArgumentException("rejection needs a problem"); } } }
Check your prediction
Text
Inserted: 2, replayed: 0
Inserted: 0, replayed: 2
Rejected: 1 problem(s)
Total: 15.75
A;FOOD;3.25
B;TRAVEL;12.50

The marked entry is Main.java. Every source tab belongs to this workspace, but only that entry's main method starts execution. Each editor has its own independent source set. To test an edit, make it in the workspace whose entry is LedgerTest.java; edits in the application editor do not carry over automatically. Download expense-ledger.zip to keep both entries and your changes together locally.

Trace an import before you run it

Exercise

Expense Ledger: trace an import

The workspace below is the real project. Its Main first imports B and A, as in the run above, then imports this batch of seven physical lines:

Text
A;FOOD;3.25

D;food;4.00
E;OTHER;1e2
B;TRAVEL;12.5
F;OTHER;2.00
B;TRAVEL;13.00

Before you run anything, write down for each line whether it inserts, replays, is skipped or becomes a problem, and with which message. Then predict whether the outcome is Accepted or Rejected, the total afterwards, and whether F is stored. Only then edit Main to print every problem as Line n: message, followed by Total: and F stored:, and compare with your trace.

Trace workspace Java
public record Accepted(int inserted, int replayed) implements ImportOutcome { public Accepted { if (inserted < 0 || replayed < 0) { throw new IllegalArgumentException("negative count"); } } } public enum Category { FOOD, TRAVEL, OTHER } import java.math.BigDecimal; import java.math.RoundingMode; /** One currency; immutable, normalized values make exact replay comparison meaningful. */ public record Expense(String id, Category category, BigDecimal amount) { public Expense { if (id == null || id.trim().isEmpty()) { throw new IllegalArgumentException("id required"); } id = id.trim(); if (id.length() > 24 || id.contains(";") || id.contains("\n") || id.contains("\r")) { throw new IllegalArgumentException("invalid id"); } if (category == null || amount == null) { throw new IllegalArgumentException("category and amount required"); } if (amount.signum() <= 0 || amount.compareTo(new BigDecimal("1000000.00")) > 0) { throw new IllegalArgumentException("amount outside 0.01..1000000.00"); } try { amount = amount.setScale(2, RoundingMode.UNNECESSARY); } catch (ArithmeticException error) { throw new IllegalArgumentException("amount needs at most two decimal places", error); } } } import java.math.BigDecimal; /** Small unquoted format: id;category;amount. Categories are case-sensitive. */ public final class ExpenseParser { public Expense parse(String line) { if (line == null || line.length() > 120) { throw new IllegalArgumentException("line missing or longer than 120 characters"); } String[] fields = line.split(";", -1); if (fields.length != 3) { throw new IllegalArgumentException("expected id;category;amount"); } String decimal = fields[2].trim(); // Reject exponents and unbounded scale before BigDecimal construction. if (!decimal.matches("[0-9]{1,7}(\\.[0-9]{1,2})?")) { throw new IllegalArgumentException("amount needs digits and up to two decimal places"); } Category category; try { category = Category.valueOf(fields[1].trim()); } catch (IllegalArgumentException error) { throw new IllegalArgumentException("category must be FOOD, TRAVEL or OTHER", error); } return new Expense(fields[0], category, new BigDecimal(decimal)); } } public sealed interface ImportOutcome permits Accepted, Rejected {} import java.io.BufferedReader; import java.io.StringReader; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** Single-threaded, in-memory atomic imports; no persistence or concurrent guarantee. */ public final class Ledger { private Map<String, Expense> entries = new LinkedHashMap<>(); private final ExpenseParser parser; public Ledger(ExpenseParser parser) { if (parser == null) { throw new IllegalArgumentException("parser required"); } this.parser = parser; } public ImportOutcome importText(String text) { if (text == null || text.length() > 12000) { return new Rejected(List.of(new Problem(0, "input missing or longer than 12000 characters"))); } Map<String, Expense> candidate = new LinkedHashMap<>(entries); List<Problem> problems = new ArrayList<>(); int inserted = 0; int replayed = 0; int lineNumber = 0; try (BufferedReader reader = new BufferedReader(new StringReader(text))) { String line = reader.readLine(); while (line != null) { lineNumber++; if (lineNumber > 100) { problems.add(new Problem(lineNumber, "more than 100 physical lines")); break; } // Even whitespace-only lines must obey the per-line size limit. if (line.length() > 120) { problems.add(new Problem(lineNumber, "line longer than 120 characters")); } else if (!line.trim().isEmpty()) { try { Expense incoming = parser.parse(line); Expense old = candidate.get(incoming.id()); if (old == null) { candidate.put(incoming.id(), incoming); inserted++; } else if (old.equals(incoming)) { replayed++; } else { problems.add(new Problem(lineNumber, "conflicting id: " + incoming.id())); } } catch (IllegalArgumentException error) { problems.add(new Problem(lineNumber, error.getMessage())); } } line = reader.readLine(); } } catch (IOException error) { throw new IllegalStateException("in-memory read failed", error); } if (candidate.size() > 100) { problems.add(new Problem(0, "ledger capacity is 100 expenses")); } if (!problems.isEmpty()) { return new Rejected(problems); } // This assignment is the only commit point. entries = candidate; return new Accepted(inserted, replayed); } public Optional<Expense> find(String id) { return Optional.ofNullable(entries.get(id)); } public List<Expense> snapshot() { return List.copyOf(entries.values()); } public BigDecimal total() { return entries.values().stream() .map(Expense::amount) .reduce(new BigDecimal("0.00"), BigDecimal::add); } public List<Expense> largestFirst() { Comparator<Expense> byAmount = Comparator.comparing(Expense::amount); return entries.values().stream() .sorted(byAmount.reversed().thenComparing(Expense::id)) .toList(); } public String exportText() { List<Expense> ordered = new ArrayList<>(entries.values()); ordered.sort(Comparator.comparing(Expense::id)); StringBuilder result = new StringBuilder(); for (Expense expense : ordered) { result.append(expense.id()).append(';') .append(expense.category()).append(';') .append(expense.amount().toPlainString()).append('\n'); } return result.toString(); } } public class Main { public static void main(String[] args) { Ledger ledger = new Ledger(new ExpenseParser()); String text = "B;TRAVEL;12.50\nA;FOOD;3.25\n"; System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText("C;OTHER;2.00\nA;FOOD;9.00"))); System.out.println("Total: " + ledger.total().toPlainString()); System.out.print(ledger.exportText()); } static String describe(ImportOutcome outcome) { return switch (outcome) { case Accepted accepted -> "Inserted: " + accepted.inserted() + ", replayed: " + accepted.replayed(); case Rejected rejected -> "Rejected: " + rejected.problems().size() + " problem(s)"; }; } } /** Line 0 means a whole-input limit or missing-input problem. */ public record Problem(int line, String message) { public Problem { if (line < 0 || message == null || message.isEmpty()) { throw new IllegalArgumentException("valid problem required"); } } } import java.util.List; public record Rejected(List<Problem> problems) implements ImportOutcome { public Rejected { problems = List.copyOf(problems); if (problems.isEmpty()) { throw new IllegalArgumentException("rejection needs a problem"); } } }
Hint 1: the idea

Read importText line by line with the batch beside it. Each line ends in one of four branches: blank and skipped, a parser exception, a replay or insert into the candidate, or a conflict. Problems do not stop the loop, and nothing is committed until the end.

Hint 2: a first step

For the parser lines, check ExpenseParser's order: field count, then the amount pattern, then the category. For B on line 5, remember what Expense's constructor does to 12.5 before the replay comparison. To print, switch on the outcome and loop over rejected.problems().

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        Ledger ledger = new Ledger(new ExpenseParser());
        ledger.importText("B;TRAVEL;12.50\nA;FOOD;3.25\n");
        String batch = "A;FOOD;3.25\n\nD;food;4.00\nE;OTHER;1e2\nB;TRAVEL;12.5\nF;OTHER;2.00\nB;TRAVEL;13.00\n";
        ImportOutcome outcome = ledger.importText(batch);
        switch (outcome) {
            case Accepted accepted -> System.out.println("Accepted: " + accepted);
            case Rejected rejected -> {
                for (Problem problem : rejected.problems()) {
                    System.out.println("Line " + problem.line() + ": " + problem.message());
                }
            }
        }
        System.out.println("Total: " + ledger.total().toPlainString());
        System.out.println("F stored: " + ledger.find("F").isPresent());
    }
}

Expected output:

Text
Line 3: category must be FOOD, TRAVEL or OTHER
Line 4: amount needs digits and up to two decimal places
Line 7: conflicting id: B
Total: 15.75
F stored: false
LineTextResult
1A;FOOD;3.25replay: equal to the stored A
2blankskipped, but counted
3D;food;4.00problem: categories are case-sensitive
4E;OTHER;1e2problem: the amount pattern rejects exponents
5B;TRAVEL;12.5replay: Expense normalizes 12.5 to 12.50
6F;OTHER;2.00staged insert, into the candidate only
7B;TRAVEL;13.00problem: same ID, different amount

Three problems make the outcome Rejected, so entries = candidate never runs. That is why F was staged on line 6 but is not stored, and the total is still 15.75. Line numbers are physical: the blank line 2 is why D is reported on line 3. Line 5 shows why normalization belongs in the constructor: without it, the retry would be a false conflict.

Change it and test again

In the trace workspace, delete line 7 from the batch and predict again: the outcome becomes Accepted, so what are the inserted and replayed counts, and what is the new total? Then trace Main's own third import, where C is staged before A conflicts. To check a change against the project's promises, make the same edit in the test workspace on Ledger Contract Tests and run LedgerTest there; edits here do not carry over.

Explain before moving on

Identify the only commit assignment in Ledger. Why does a rejected result expose problems rather than candidate counts? Explain how immutable Expense records and a private candidate map cooperate to prevent partial state changes.

Was this article helpful?

Your response is saved on this device.