Combine a unique-key index with a deterministic report. The catalog stores one immutable product per ID. Reports order those products without exposing the private index or changing its insertion order. This is a reusable pattern for many small applications.
Understand the contract
The contract has two different orderings. Storage keeps first-insertion order so a snapshot is predictable. The report sorts by descending stock, then ID ascending. Those orders must not accidentally overwrite each other. Sorting a copied list preserves the index while giving a report the order it needs.
Records make product values easy to share, but stock validity still needs a constructor check in the full exercise. For this small catalog, a product's stock is a nonnegative int; the ID is nonblank trimmed text. Zero stock is valid and must remain visible. A duplicate ID is an error even if the title or stock differs.
The example uses insertion-order values copied from a LinkedHashMap. values() is a collection view backed by the map; wrapping it in new ArrayList creates the separate container we actually want to sort. Do not return a writable map view as though it were an independent snapshot.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("B", 2);
stock.put("A", 5);
List<String> ids = new ArrayList<>(stock.keySet());
ids.sort(String::compareTo);
System.out.println(ids);
System.out.println(new ArrayList<>(stock.keySet()));
}
}Check your prediction
[A, B]
[B, A]Trace a different case
A returned unmodifiable list protects its container. Because its Product elements are records of immutable components, callers cannot change the catalog through an element either. This would not be true for a record holding a mutable list. The small example below shows a report snapshot that remains valid after the local result builder is cleared.
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<Product> builder = new ArrayList<>();
builder.add(new Product("A", 5));
List<Product> report = List.copyOf(builder);
builder.clear();
System.out.println(report.get(0).id());
System.out.println(report.size());
}
}
record Product(String id, int stock) {}Check your prediction
A
1Plan your acceptance cases
Before writing the complete implementation, predict these cases without running the solution. Keep the requirements above as the authority; this table highlights distinct promises rather than prescribing a particular class layout.
| Case | Expected behavior | Skill it checks |
|---|---|---|
| Two products tied on stock | ID ascending within the tie | Secondary order |
| Duplicate normalized ID | Reject rather than overwrite | Index identity |
| Zero stock and empty source | Both valid; report may be empty | Boundary and ownership |
After your first version works, choose one row and introduce a plausible defect that it should expose. Restore the correct version, then recreate the central operation without the worked example. If one skill is missing, revisit that lesson before combining more features.
Build it yourself
Checkpoint: Catalog Report: practice
Write report(List<Product>) that builds a unique-ID index, rejects duplicate IDs, then returns an unmodifiable list ordered by descending stock and ascending ID. Validate Product IDs and stock in its compact constructor. For B/2, C/5, A/5 print IDs A, C, B, one per line. Check a zero-stock product is valid and duplicate IDs reject before returning a report.
public class Main {
public static void main(String[] args) {
// Add your implementation and checks below.
System.out.println("Your workspace");
}
}Hint 1: the idea
Use one map to enforce identity and one copied list to define report order.
Hint 2: a first step
Reverse only the stock comparator, then append the ascending ID tie-breaker.
Show one solution
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
for (Product product : report(List.of(new Product("B", 2), new Product("C", 5), new Product("A", 5)))) {
System.out.println(product.id());
}
if (new Product("Z", 0).stock() != 0) {
throw new AssertionError("zero stock");
}
try {
report(List.of(new Product("A", 1), new Product("A", 2)));
throw new AssertionError("duplicate accepted");
} catch (IllegalArgumentException expected) {
// Duplicate IDs are rejected.
}
}
static List<Product> report(List<Product> products) {
Map<String, Product> index = new LinkedHashMap<>();
for (Product product : products) {
if (index.containsKey(product.id())) {
throw new IllegalArgumentException("duplicate id");
}
index.put(product.id(), product);
}
List<Product> result = new ArrayList<>(index.values());
Comparator<Product> byStock = Comparator.comparingInt(Product::stock);
result.sort(byStock.reversed().thenComparing(Product::id));
return List.copyOf(result);
}
}
record Product(String id, int stock) {
Product {
if (id == null || id.trim().isEmpty() || stock < 0) {
throw new IllegalArgumentException("invalid product");
}
id = id.trim();
}
}Expected output:
A
C
BThe index is built and checked completely before any sorting, so a duplicate
throws before a report exists. The comparator is
byStock.reversed().thenComparing(Product::id): reversing only the stock part
keeps the ID tiebreak ascending, which is why A comes before C when both have
5. Calling .reversed() after thenComparing would have reversed the IDs too.
Change it and test again
Test empty input, equal stocks and padded IDs that normalize to the same key. Try reversing the complete comparator chain: which two products swap unexpectedly? Add a check that editing the returned list fails, and another that the caller's source order remains unchanged.
Explain before moving on
Where are identity, value validity, report order and ownership enforced? Would a PriorityQueue improve this one-off report? Justify a simple choice based on the workload rather than adding every collection you have learned.
Completion is saved in this browser only. It does not measure mastery.