Skip to content
Tutorials Center
My learning

Topics

Lesson 176 of 201 ยท Projects

Project: Inventory Manager

Build a Java inventory manager in stages. Parse CSV data into validated records, store products in a map, update stock immutably and build stream reports.

Every shop, warehouse and online store runs on an inventory: what do we have, how much is it worth, and what do we need to reorder? The data usually arrives as a spreadsheet export, a CSV file full of rows that are almost right. Turning that into reliable answers is one of the most common jobs in real-world Java, and it's a perfect fit for the modern tools you've learned: records, collections, streams and Optional.

In this project you'll build an inventory manager for a small electronics shop, in five stages: parse CSV rows into validated records, handle real CSV with quoted fields, store products in a map with immutable updates, produce reports with streams, and finally run the whole thing from commands in the Input box. Each stage is a complete program.

The project leans on records, HashMap and TreeMap, streams, collectors, Optional, Comparator and BigDecimal. Where the bank and library projects focused on objects that enforce rules, this one is about data pipelines: data comes in, gets checked, transformed and summarized.

The data

The shop exports its products as CSV (comma-separated values) with a header row:

TEXT
sku,name,category,price,quantity,reorder
KB-101,Mechanical Keyboard,Peripherals,89.90,14,5
MN-201,27-inch Monitor,Displays,229.00,6,3

Each product has a SKU (stock-keeping unit: a short unique code like KB-101), a name, a category, a unit price, the quantity in stock and a reorder level: when stock falls to that number or below, it's time to order more. The program's rules:

  • A SKU is 2โ€“4 capital letters, a dash and three digits. Lowercase input is accepted and normalized.
  • Prices are zero or more with at most two decimals; quantities and reorder levels are whole numbers, never negative.
  • SKUs are unique. A bad row is reported with its line number and skipped; the good rows still load.

Stage 1: parsing rows into records

A product is a bundle of values that belong together, and a validated product should never become invalid: a record with a compact constructor is exactly that. The parser's job is to turn text into the right types and collect every problem it finds, instead of stopping at the first one.

Java Stage 1: CSV rows to validated records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Four rows load and five problems are reported, each with a line number you could look up in the original file. The lowercase SKU ms-102 was quietly normalized to MS-102.

Design choices in this stage:

  • The data lives in a text block for now, so the stage is self-contained. DATA.lines().toList() splits it into lines. The loop starts at index 1 to skip the header, and lineNumber is i + 1 because people count lines from 1.
  • Parsing and validating are separate steps. parseRow only converts text into types (BigDecimal, int), translating Java's NumberFormatException into a message that names the field. The record's compact constructor then checks the rules. A Product built anywhere else in the program (not from CSV) gets the same checks for free.
  • The SKU check uses a regex. [A-Z]{2,4}-\\d{3} reads "two to four capital letters, a dash, three digits". String.matches requires the whole string to match. The Regular Expressions lesson explains the syntax.
  • split(",", -1) keeps empty trailing fields. With a plain split(","), a row like A,B,,,, would silently lose its empty fields at the end and report the wrong count. The -1 limit means "keep everything", which is what a parser wants.
  • Errors are collected, not thrown out of the loop. One bad row shouldn't hide the others. Collecting messages in a list gives the user the whole picture in one run, just like a compiler listing all its errors.
  • Duplicates are detected with Set.add, which returns false when the element is already there. One call checks and records the SKU.

Stage 2: real CSV has quotes

Stage 1's split(",") has a flaw that every CSV parser written in a hurry shares. What if a product name contains a comma, like Cable, USB-C to HDMI? CSV's answer is quoting: fields that contain commas are wrapped in double quotes, and a literal quote inside a quoted field is written twice (""). A plain split breaks such rows into too many pieces.

Parsing quoted CSV needs a tiny state machine: walk through the line character by character, remembering whether you're currently inside quotes.

Java Stage 2: a CSV splitter that understands quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The quoted name "Cable, USB-C to HDMI" stays one field, "" becomes a single " in Monitor 24" IPS, and an unclosed quote is reported instead of silently swallowing the rest of the line. The last line of output shows what the naive split does to the same row: seven fields instead of six, with the name torn in half and its quote marks left in.

How the state machine works:

  • Outside quotes, a comma ends the current field, a quote switches into quoted mode, and anything else is part of the field.
  • Inside quotes, a comma is just a character. A quote either ends quoted mode or, if the next character is also a quote, stands for one literal quote; i++ then skips the second one.
  • StringBuilder collects the characters of the current field, and setLength(0) clears it for the next one without creating a new builder. See StringBuilder.
  • After the loop, the last field is added, because a line doesn't end with a comma. Forgetting that final add is the classic bug in hand-written splitters.

This handles the CSV you'll meet in most exports. Full CSV also allows line breaks inside quoted fields, which needs a parser that reads across lines; for production work a library such as Apache Commons CSV or Jackson's CSV module handles every corner case. Writing one yourself once is still the best way to understand what those libraries do.

From now on, the program uses splitCsv instead of split(",").

Stage 3: the inventory and immutable updates

Parsed products now go into an Inventory class that answers questions and records sales. Two design questions come up immediately.

Which map? Products are looked up by SKU, so a map keyed by SKU is natural. A TreeMap keeps keys sorted, so every listing comes out in SKU order without extra work; with a few thousand products its O(log n) lookups are effectively instant.

How do you change a record? You don't. A record's fields are final, so selling three keyboards creates a new Product with a smaller quantity and puts it into the map in place of the old one. Methods that return a modified copy are often called withers (withQuantity, withPrice).

Java Stage 3: lookups with Optional and immutable stock updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Points to notice:

  • find returns Optional<Product>, because "no such SKU" is a normal answer to a lookup. Callers choose how to deal with absence: main uses map(Product::name).orElse("not found") to print a fallback, while require uses orElseThrow to turn absence into an InventoryException for operations that can't continue without a product. One lookup method, two clear policies. The Optional lesson covers these methods.
  • Immutability makes history safe. before still says 6 after the sale, because the sale created a new record. Any code holding an old Product (a report being printed, a sale record) can't be surprised by a change underneath it. The cost is one small object per update, which is nothing for an inventory.
  • Withers reuse validation. withPrice calls the canonical constructor, so reprice with a negative price fails the same check as a bad CSV row. reprice translates that IllegalArgumentException into an InventoryException so callers have one exception type to catch.
  • Sales are records too. Each Sale captures the price at the moment of sale. If the price changes later, past revenue doesn't change, which is exactly what an accountant expects.
  • sell checks everything before changing anything, the same discipline as in the bank project.

Stage 4: reports with streams

Now the questions a shop owner actually asks: What's my stock worth? Worth per category? What must I reorder? Where is my money tied up? Each answer is a short stream pipeline over the products.

Java Stage 4: stream reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each report method is a few lines, and each reads like the question it answers. A tour of the techniques:

  • reduce(BigDecimal.ZERO, BigDecimal::add) sums BigDecimal values. There's no sum() for object streams (that exists only on IntStream and friends), so you supply the starting value and the combining function. BigDecimal.ZERO is the identity: adding it changes nothing, which is what reduce requires.
  • groupingBy with three arguments takes a key function, a map factory and a downstream collector. TreeMap::new makes the categories come out sorted, and Collectors.reducing(BigDecimal.ZERO, Product::stockValue, BigDecimal::add) sums the stock values inside each group. countByCategory uses the same shape with counting(). Collecting Stream Results explains downstream collectors.
  • The reorder list sorts by urgency: quantity - reorderLevel is how far below (or at) the reorder level a product is, so the most urgent products come first. HDMI cables (25 in stock, reorder at 30, so -5) top the list, ahead of the Desk Speakers (0 versus 3, so -3) and the Portable Monitor (2 versus 2, so 0). You could argue that an empty shelf is more urgent than a short one; a rule like that is a business decision, and it's worth writing down which one you chose.
  • max(Comparator.comparing(Product::price)) returns an Optional<Product>, empty if the inventory is empty. Again, absence is explicit in the type.
  • %,10.2f prints a BigDecimal with thousands separators, two decimals and a width of 10, so the values line up.

The explicit (Product p) in lowStock is needed for the same reason as in the library project: a lambda followed by a chained comparator method can't infer its parameter type.

Stage 5: the complete inventory manager

The final program reads the CSV from the Input box (up to the first blank line), reports any rows it skipped, then executes commands from the remaining lines. Everything from the earlier stages comes together: the quote-aware parser, validated records, the map with immutable updates, sales and the stream reports.

Java Stage 5: the complete inventory manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try your own commands, or paste a different product list above the blank line. A few final design notes:

A parser that returns a result object

ProductParser.parse returns a ParseResult record holding both the products and the errors. A method can return only one value, and a small record is the cleanest way to return two related ones; it's the "returning multiple values with records" idea from Parameters and Return Values. Both lists are wrapped with List.copyOf, so nobody can change them later.

ParseError is a record instead of a plain string, so a future version could sort errors, count them by type, or highlight the line in a user interface, all without parsing message text.

ProductParser is a utility class: final, with a private constructor and only static methods. Nothing about parsing needs per-object state.

Two exception types, one boundary

Inside the parser and the records, rule violations are IllegalArgumentException: they're about values being invalid. The parser catches them per row and turns them into ParseErrors. Inventory and the command layer use InventoryException for operations that can't be performed. Wherever a value error crosses into an operation (as in reprice and parsePrice), it's translated, so the command loop has exactly one exception type to catch. Choosing a clear boundary for each exception type keeps catch blocks simple.

Reading two kinds of input from one stream

The Input box holds data first and commands second, separated by a blank line. The first loop reads until it sees that blank line and breaks; the second loop continues with the same Scanner, picking up right where the first stopped. One Scanner per input stream is the rule: creating a second Scanner on System.in could lose input the first one had already buffered.

Ideas to extend it

  • Purchase orders. Add an order command that lists every low-stock product with a suggested order quantity (for example, enough to reach twice the reorder level) and the cost of the whole order.
  • Export CSV. Write the current inventory back out as CSV, quoting any field that contains a comma or quote, so it round-trips through splitCsv. Use Files to save it.
  • Price history. Keep a List<PriceChange> record list and report the biggest price changes.
  • Categories as an enum. Replace the free-text category with an enum Category, and decide how to report rows with unknown categories.
  • Margins. Add a cost price column and report profit per sale and per category with groupingBy.
  • Undo. Because products are immutable, undo is easy: keep the previous Product for every change on a stack (ArrayDeque) and put it back on undo.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "A,B,,".split(",").length return, and why does the parser use split(",", -1)?

    Without a limit, split removes trailing empty strings, so "A,B,," gives [A, B]. A negative limit keeps every field, so the parser sees the real field count.
  2. 2. The CSV splitter is given the line X,"a ""quoted"" word",Y. How many fields does it return, and what is the second one?

    Inside quotes, commas don't split, and each doubled quote becomes one literal quote character. The result is X, a "quoted" word, and Y.
  3. 3. After Product after = inventory.sell("MN-201", 4);, what happens to a Product before obtained just before the sale?

    sell creates a new Product with withQuantity and replaces the map entry. The old record is untouched, which is what makes it safe to keep.
  4. 4. Why does totalValue use reduce(BigDecimal.ZERO, BigDecimal::add) instead of sum()?

    A Stream of BigDecimal objects has no sum method. reduce combines the elements with add, starting from the identity value ZERO.
  5. 5. Which collector produces a sorted Map<String, Long> from category to number of products?

    groupingBy with a TreeMap factory sorts the keys, and the counting downstream collector counts the elements in each group.

Summary

  • Parse in two steps: convert text to types (translating NumberFormatException into clear messages), then let a record's compact constructor enforce the rules.
  • Collect parse errors with line numbers instead of stopping at the first one; split(",", -1) keeps empty fields, and real CSV needs a small quote-aware state machine.
  • A TreeMap keyed by SKU gives sorted listings; find returns Optional, and orElseThrow turns absence into an exception where an operation needs a product.
  • Records are updated by replacing them with "wither" copies, which keeps history and old references safe.
  • Stream reports use reduce for BigDecimal sums, groupingBy with TreeMap::new and downstream collectors, Comparator chains and max.
  • A result record returns products and errors together; one exception type per boundary keeps the command loop simple.

Next: Project: Text Analyzer, where you'll count words, find patterns with regular expressions and rank the results.