A shop owner likes a quick summary of the shop: how many products it has, the lowest and the highest price, and the average price. None of these numbers is stored. Your route works them out from the products on every request, so they always match the shop.
All four come from the list of prices. prices.size() counts the items, Collections.min and Collections.max find the smallest and the largest, and the sum helper, already in your file, adds them up. The average is the sum divided by the count. Math.round rounds to a whole number, so to keep 2 decimal places you multiply by 100.0, round, then divide by 100.0. The same tools on other numbers:
List<Integer> ages = List.of(30, 25, 40);
System.out.println(ages.size() + " " + Collections.min(ages) + " " + Collections.max(ages)); // 3 25 40
System.out.println(Math.round(sum(ages) * 100.0 / ages.size()) / 100.0); // 31.67
An empty list has no smallest number: Collections.min throws an exception on it, and the route crashes with a 500. So when the shop has no products, answer the count 0 and no value for the other three. Map.of refuses null, so use Optional.empty(): Spring sends it as JSON's null, which means "no value".
Your code must answer these requests, in this order:
GET /stats → 200 {"count": 4, "cheapest": 2, "most_expensive": 29, "average_price": 12.5}
DELETE /products/1 → 204
GET /stats → 200 {"count": 3, "cheapest": 2, "most_expensive": 29, "average_price": 12.67}
DELETE /products/2, then /products/3, then /products/4 → 204 each
GET /stats → 200 {"count": 0, "cheapest": null, "most_expensive": null, "average_price": null}
POST /products {"name": "Chair", "price": 45, "category": "furniture"} → 201
GET /stats → 200 {"count": 1, "cheapest": 45, "most_expensive": 45, "average_price": 45}
Your task: add a route for GET /stats that answers count, cheapest, most_expensive and average_price (rounded to 2 places), with null for the last three when the shop is empty.
Assignment
Follow the Coding Tutorial to build the getStats method for GET /stats: collect the prices, handle an empty shop, work out the average, and answer the four keys.
Hint
Check for an empty list right after the loop, before Collections.min and the division. Write 100.0, not 100: when both numbers are whole, Java's division drops the decimals.
Free plan: 30 tutor messages. PRO is unlimited.
