You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按Category计算建筑平均价格的Map返回函数?

实现按建筑类别计算平均价格的函数

需求说明

需要实现函数 Map<Category, Double> averagePricePerCategory(List<Building> buildings):

  • 参数:建筑列表 List<Building>,每个 Building 对象包含属性:
    • private int price;
    • private String neighborhood;
    • private Category category;
  • 功能:计算每个 Category 对应的建筑平均价格,返回包含类别与对应平均价格的 Map

现有代码的问题

你当前的代码存在几个关键问题:

  1. 初始化的 averagePriceCategory 是 Map<String, Double>,但函数返回类型是 Map<Category, Double>,类型不匹配
  2. 在判断列表是否为空之前就调用 buildings.get(0).getCategory(),会导致空列表时抛出 IndexOutOfBoundsException
  3. 循环体为空,未实现累加计算逻辑,最后返回 null 不符合需求(空列表应返回空Map,非空列表需返回计算后的Map)

解决方案

方案1:传统循环实现

这种方式逻辑清晰直观,适合不使用Java 8+ Stream API的场景:

import java.util.HashMap;
import java.util.List;
import java.util.Map;

static Map<Category, Double> averagePricePerCategory(List<Building> buildings) {
    // 空列表直接返回空Map
    if (buildings.isEmpty()) {
        return new HashMap<>();
    }

    // 用两个Map分别存储每个类别的总价格和建筑数量
    Map<Category, Integer> totalPriceMap = new HashMap<>();
    Map<Category, Integer> countMap = new HashMap<>();

    for (Building b : buildings) {
        Category category = b.getCategory();
        // 累加当前类别的总价格
        totalPriceMap.put(category, totalPriceMap.getOrDefault(category, 0) + b.getPrice());
        // 累加当前类别的建筑数量
        countMap.put(category, countMap.getOrDefault(category, 0) + 1);
    }

    // 计算平均值并构建结果Map
    Map<Category, Double> averageMap = new HashMap<>();
    for (Category category : totalPriceMap.keySet()) {
        int totalPrice = totalPriceMap.get(category);
        int count = countMap.get(category);
        averageMap.put(category, (double) totalPrice / count);
    }

    return averageMap;
}

方案2:Java 8+ Stream API实现

利用Stream的收集器可以更简洁地完成需求,代码紧凑易读:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

static Map<Category, Double> averagePricePerCategory(List<Building> buildings) {
    return buildings.stream()
            .collect(Collectors.groupingBy(
                    Building::getCategory,
                    Collectors.averagingInt(Building::getPrice)
            ));
}
  • Collectors.groupingBy 按 Category 对建筑进行分组
  • Collectors.averagingInt 自动计算每组的平均价格,直接返回Double类型的平均值

内容的提问来源于stack exchange,提问作者Lucian Negru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:25:19