面试题答案
一键面试设计思路
- 遍历
List<Order>
,对于每个Order
,根据customerId
将其分组。 - 对于每个分组,累加订单金额得到该客户的总订单金额。
- 同时,遍历每个
Order
中的List<OrderItem>
,根据productId
统计每种产品的总数量。
核心代码实现(Java 示例)
import java.util.*;
class Order {
private int orderId;
private int customerId;
private double orderAmount;
private List<OrderItem> orderItems;
public Order(int orderId, int customerId, double orderAmount, List<OrderItem> orderItems) {
this.orderId = orderId;
this.customerId = customerId;
this.orderAmount = orderAmount;
this.orderItems = orderItems;
}
public int getCustomerId() {
return customerId;
}
public double getOrderAmount() {
return orderAmount;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
}
class OrderItem {
private int productId;
private int quantity;
public OrderItem(int productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public int getProductId() {
return productId;
}
public int getQuantity() {
return quantity;
}
}
public class Main {
public static void main(String[] args) {
List<Order> orders = new ArrayList<>();
// 初始化 orders 数据
Map<Integer, Map<String, Object>> result = new HashMap<>();
for (Order order : orders) {
int customerId = order.getCustomerId();
result.putIfAbsent(customerId, new HashMap<>());
Map<String, Object> customerData = result.get(customerId);
double totalAmount = customerData.containsKey("totalAmount")
? (double) customerData.get("totalAmount") : 0;
totalAmount += order.getOrderAmount();
customerData.put("totalAmount", totalAmount);
Map<Integer, Integer> productQuantityMap = customerData.containsKey("productQuantities")
? (Map<Integer, Integer>) customerData.get("productQuantities") : new HashMap<>();
for (OrderItem item : order.getOrderItems()) {
int productId = item.getProductId();
int quantity = item.getQuantity();
productQuantityMap.put(productId, productQuantityMap.getOrDefault(productId, 0) + quantity);
}
customerData.put("productQuantities", productQuantityMap);
}
System.out.println(result);
}
}
上述代码首先定义了 Order
和 OrderItem
类,然后在 main
方法中对 List<Order>
进行遍历,通过 Map
实现按 customerId
分组统计每个客户的总订单金额以及每个客户购买的每种产品的总数量。