← All Exercises

Aggregate Order Spend with flatMap

intermediatejava~20min

Background

Nested JSON-like data is common in commerce. Flattening with flatMap and folding with summingDouble avoids manual loops and mutable accumulators.

Problem

Given orders, each with a customer and a list of items, compute total spend per customer by flattening items, grouping amounts, and sorting descending.

Input

A list of Order records, each with a non-null customer name and a list of Item records holding quantity and unitPrice.

Output

Customer names paired with total spend, ordered by spend descending then name ascending, printed with two decimal places.

Sample tests

Sample 1

Input: alice: 1 x 79.00 and 1 x 25.50; bob: 2 x 79.00; alice: 3 x 4.25
Expected: bob 158.00
alice 117.25

Sample 2

Input: carol: 1 x 10.00 only
Expected: carol 10.00

Your solution

Learning objective

Compose flatMap line expansion with grouping collectors and produce deterministic sorted aggregates.