题目
定义 Item(sku、quantity、unitPrice)与 Order(customer、items 列表)两个记录类型。要求计算每位客户在所有订单上的总消费,返回“客户名-金额”条目列表,按金额降序排列,金额相同时按客户名升序。打印时金额保留两位小数。商品列表可能为空,订单可能属于同一客户多笔。
解题思路
用 flatMap 把每笔订单展开成若干 Line(customer, amount),在商品层面完成数量乘单价,嵌套结构因此变成扁平的费用流。随后用 Collectors.groupingBy(Line::customer, Collectors.summingDouble(Line::amount)) 一次遍历汇总每位客户消费,避免手工维护可变累加器。排序时手写比较器:先用 Double.compare 比较金额并取反实现降序,金额相同再用 String.compareTo 比较姓名,保证结果稳定。空商品列表不产生任何 Line,自然不会影响汇总。
参考实现要点
- 数量乘以单价必须在单件商品层面完成,不能只累加单价。
- 金额是 double,比较时使用 Double.compare,避免直接相减的精度与溢出问题。
- groupingBy 的下游收集器直接给出汇总值,返回 Map<String, Double>。
- 先排序再收集,输出顺序完全由比较器决定,与 HashMap 遍历顺序无关。
常见错误
把单价之和当作消费额,忽略 quantity 会导致金额偏小。使用减法比较 double 在极端值下可能溢出,也不符合浮点比较习惯。只按金额排序而不加姓名平局键,金额相同的客户顺序可能每次不同。对空列表调用 get(0) 之类的操作会抛异常,而流式 sum 天然返回 0。
验证方式
运行 main 方法,应输出 bob 158.00 与 alice 117.25,且 bob 在前。构造两位消费额相同的客户,确认按姓名升序排列。加入一笔包含两件商品的订单,核对金额确实乘以数量。最后加入商品列表为空的订单,确认该客户金额不受影响且程序不抛异常。
代码示例
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CustomerSpend {
record Item(String sku, int quantity, double unitPrice) {}
record Order(String customer, List<Item> items) {}
record Line(String customer, double amount) {}
static List<Map.Entry<String, Double>> spendByCustomer(List<Order> orders) {
Map<String, Double> totals = orders.stream()
.flatMap(order -> order.items().stream()
.map(item -> new Line(
order.customer(),
item.quantity() * item.unitPrice())))
.collect(Collectors.groupingBy(
Line::customer,
Collectors.summingDouble(Line::amount)));
return totals.entrySet().stream()
.sorted((a, b) -> {
int byAmount = Double.compare(b.getValue(), a.getValue());
return byAmount != 0
? byAmount
: a.getKey().compareTo(b.getKey());
})
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("alice", List.of(
new Item("KB-01", 1, 79.0),
new Item("MS-02", 1, 25.5))),
new Order("bob", List.of(
new Item("KB-01", 2, 79.0))),
new Order("alice", List.of(
new Item("CB-03", 3, 4.25))));
for (Map.Entry<String, Double> entry : spendByCustomer(orders)) {
System.out.printf("%s %.2f%n", entry.getKey(), entry.getValue());
}
}
}