← Back to Week 3 Hub
Workbook 3a — Exercise

Search Inventory (Map Version)

Look up products by name using a HashMap instead of a list  |  Workbook p.62

The Exercise

Rebuild the inventory program, but this time use a HashMap<String, Product> keyed by product name. The user will type a product name, and you look it up instantly using inventory.get(name). Load the products from inventory.csv at startup. If the product is in stock, show its details. If not, tell the user it's not carried.

Why a HashMap here? With an ArrayList you would loop through every product and compare names. A HashMap keyed by name gives you the answer in one call — it's built for fast lookups by key.
Example Runs
Run 1 — Product found
Enter product name: Hammer

Hammer — $19.49
Run 2 — Product not carried
Enter product name: Sundae

We don't carry that product.
Run 3 — Bonus: search again loop
Enter product name: Hammer
Hammer — $19.49

Search again? (Y/N): Y
Enter product name: Cordless Drill
Cordless Drill — $89.00

Search again? (Y/N): N
Goodbye!
Concepts You'll Use
Flow
Create Product class id, name, price + getters
loadInventory() Reads CSV → HashMap<String,Product>
Prompt for name User types a product name
inventory.get(name) Is the result null?
Found Print name and price
  
Not found "We don't carry that product"
Bonus: search again? Loop until user enters N

Workbook 3a, p.62 — Exercise: Search Inventory (Map)

← Search Inventory (ArrayList) User Stories (Hardware Store) →