Start learning free

LESSON 28 OF 173 · BACKEND: YOUR FIRST API

Sort the List in Java

Practice

Clients often want a list in a useful order: the cheapest products first, or names from A to Z. A Java list can sort itself with list.sort(...). It can't compare two maps, though, so you tell it what to compare with a key method: a method that takes one item and returns the value to sort by. Comparator.comparing turns that method into a comparator.

static int byStars(Map<String, Object> review) {
    return (int) review.get("stars");
}

// reviews: [{"user": "ana", "stars": 5}, {"user": "bo", "stars": 3}]
reviews.sort(Comparator.comparing(ReviewController::byStars));
// now: [{"user": "bo", "stars": 3}, {"user": "ana", "stars": 5}]

Write ReviewController::byStars without parentheses: you hand over the method itself, and the comparator calls it on each item. list.sort changes the order of that list, so sort a list you made for this request, never the shop's own products.

The client picks the order with a query parameter: ?sort=price or ?sort=name. Any other value is a mistake, so the shop answers 400 with an error. Without sort, the list keeps the shop's order, and the filters still work. The lists below show product names only; each item is a full product.

GET /products?sort=price  →  200  [Pen, Notebook, Mug, Lamp]
GET /products?sort=name  →  200  [Lamp, Mug, Notebook, Pen]
GET /products  →  200  [Mug, Notebook, Lamp, Pen]
GET /products?category=office&sort=price  →  200  [Pen, Notebook]
GET /products?sort=color  →  400  {"error": "Sort must be price or name"}

Your task: write two static key methods, byPrice and byName. In getProducts, which now takes String sort, answer 400 for an unknown sort, and sort the filtered list by price or by name.


Assignment
Follow the Coding Tutorial to add sorting to GET /products.


Hint
Sort result after the filter loop, so only the products that passed the filters get sorted. Check with "price".equals(sort): it is simply false when sort is null, while sort.equals("price") would crash.


STEP 1 OF 10
    Ctrl + Enter to check

    Shop Sort 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