Part 09 / Topic 10 of 10
Putting it together: a sales report via streams
Real-world example: a small shop's monthly sales, combining this part's ideas the way real code does — a tiny generic repository, Comparator-based ranking, a streams pipeline for the numbers, and Optional for a safe lookup.
class Repository<T> {
private final List<T> items;
Repository(List<T> items) { this.items = items; }
List<T> all() { return items; }
Optional<T> findFirst(Predicate<T> match) { return items.stream().filter(match).findFirst(); }
}
Total revenue, the whole point of a sales report, is one reduce-shaped line:
double totalRevenue = sales.all().stream().mapToDouble(Sale::amount).sum();
Total revenue: Rs. 6820.00
Revenue by city groups and sums in the same call, then the result is just a Map you can print or chart:
Chennai Rs. 900.00
Delhi Rs. 2725.00
Pune Rs. 3195.00
Ranking cities by revenue reuses Map.Entry.comparingByValue(), a ready-made Comparator for exactly this "sort a map's entries by value" job, the same idea as section 4's Comparator but supplied by the library:
List<String> rankedCities = revenueByCity.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.map(Map.Entry::getKey)
.toList();
ranking: [Pune, Delhi, Chennai]
And the safe lookups, exactly as section 9 described them — filter to add a rule, orElse/ifPresentOrElse so a missing result is handled in the same line it is discovered, never a silent null:
found a Pune sale over Rs. 1000: S-01
no sales recorded for Mumbai
The full report is one pipeline, sorted then map then collected into lines, read top to bottom exactly like the rest of this part's examples:
S-04 | Chennai | Eraser | qty 300 | Rs. 900.00
S-02 | Delhi | Pen | qty 200 | Rs. 1600.00
S-06 | Delhi | Notebook | qty 25 | Rs. 1125.00
S-01 | Pune | Notebook | qty 40 | Rs. 1800.00
S-03 | Pune | Notebook | qty 15 | Rs. 675.00
S-05 | Pune | Pen | qty 90 | Rs. 720.00
Nothing here is a new idea — it is sections 1–9, chosen and combined the way a real report would need them.
Full program: examples/SalesReportStreams.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.