Start learning free

LESSON 31 OF 173 · BACKEND: YOUR FIRST API

List the Categories in Java

Practice

A shop's front page often shows a menu of its categories. The shop keeps no list of them: each product only knows its own category. So your API builds the list from the products, every time someone asks.

The list must be distinct: two products are in "office", but the menu shows it once. Before adding a value to a list, !list.contains(value) tells you the list doesn't hold it yet. Then Collections.sort puts a list of Strings in alphabetical order, with no comparator. The same idea on a list of colors:

List<String> colors = new ArrayList<>();
for (String color : List.of("red", "blue", "red")) {
    if (!colors.contains(color)) {
        colors.add(color);
    }
}
Collections.sort(colors);
System.out.println(colors);   // [blue, red]

The list is built from the products on every request, so it always follows them. A product in a new category adds that category, and deleting the only product of a category removes it. Your code must answer these requests, in this order:

GET /categories  →  200  ["home", "kitchen", "office"]
POST /products  {"name": "Chair", "price": 45, "category": "furniture"}  →  201  {"id": 5, "name": "Chair", …}
POST /products  {"name": "Stapler", "price": 9, "category": "office"}  →  201  {"id": 6, "name": "Stapler", …}
GET /categories  →  200  ["furniture", "home", "kitchen", "office"]
DELETE /products/3  →  204
GET /categories  →  200  ["furniture", "kitchen", "office"]

Your task: add a method for GET /categories that answers the distinct categories of the products, in alphabetical order, as a JSON list.


Assignment
Follow the Coding Tutorial to build the GET /categories method: an empty list, a loop over products, a contains check, and a sorted answer.


Hint
Add a category only when categories doesn't contain it yet. A list of Strings needs no comparator: Collections.sort(categories) puts it in alphabetical order, and java.util.Collections is already imported.


STEP 1 OF 7
    Ctrl + Enter to check

    Shop Categories in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free