Start learning free

LESSON 30 OF 173 · BACKEND: YOUR FIRST API

Only the First Few

Practice

A real shop can have thousands of products, and a page often shows only a few. A client asks for that with a query parameter: ?limit=2 means "at most 2 products".

To keep the first few items of a list, use subList. items.subList(0, n) goes from the start up to, but not including, position n. It can't reach past the end of the list, so Math.min keeps n within the list's size.

List<String> days = List.of("Mon", "Tue", "Wed", "Thu", "Fri");
System.out.println(days.subList(0, 2));                          // [Mon, Tue]
System.out.println(days.subList(0, Math.min(10, days.size())));  // the whole list
// days.subList(0, 10) would throw an error: days has only 5 items

Cut the list last, after filtering and sorting, so ?sort=price&limit=2 gives the two cheapest products. A limit of 0 or less makes no sense, so it gets 400. Without limit, the answer is the whole list, as before. The lists below show product names only.

GET /products?limit=2  →  200  [Mug, Notebook]
GET /products?sort=price&limit=2  →  200  [Pen, Notebook]
GET /products?category=office&limit=1  →  200  [Notebook]
GET /products?limit=10  →  200  [Mug, Notebook, Lamp, Pen]
GET /products?limit=0  →  400  {"error": "Limit must be 1 or more"}
GET /products?limit=-3  →  400  {"error": "Limit must be 1 or more"}

Your task: in getProducts, which already takes Integer limit, answer 400 when the limit is less than 1, and cut the list to its first limit products.


Assignment
Follow the Coding Tutorial to add a limit to GET /products.


Hint
limit is null when the URL has none, like max_price. Check it before the loop, and cut result with subList just before the return, after the sorting.


STEP 1 OF 4
    Ctrl + Enter to check