MST

星途 面试题库

面试题:Java利用Map接口优化复杂数据结构的分组与统计

给定一个复杂的数据结构List<Order>,Order类包含属性orderId(订单ID)、customerId(客户ID)、orderAmount(订单金额)以及一个List<OrderItem>,OrderItem类包含productId(产品ID)和quantity(数量)。要求使用Map接口,按customerId分组统计每个客户的总订单金额以及每个客户购买的每种产品的总数量,描述设计思路并给出核心代码实现。
21.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 遍历 List<Order>,对于每个 Order,根据 customerId 将其分组。
  2. 对于每个分组,累加订单金额得到该客户的总订单金额。
  3. 同时,遍历每个 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);
    }
}

上述代码首先定义了 OrderOrderItem 类,然后在 main 方法中对 List<Order> 进行遍历,通过 Map 实现按 customerId 分组统计每个客户的总订单金额以及每个客户购买的每种产品的总数量。