Java中修正按唯一国家代码统计人口总和的Map逻辑错误
问题描述
数据

CountryInfo类
public class CountryInfo { private String country; private String countryCode; private String currency; @Id private String state; private String stateCode; private String statePopulation; }
当前实现的方法:
public HashMap<String, Integer> getAllCountryPopulations(){ List<CountryInfo> countries = countrySqlRepository.findAll(); HashMap<String, Integer> populations = new HashMap<>(); Integer sumOfPopulation = 0; HashSet<String> set = new HashSet<String>(); for(int i=0; i<countries.size(); i++){ CountryInfo countryInfo = countries.get(i); set.add(countryInfo.getCountryCode()); if(set.contains(countryInfo.getCountryCode())){ sumOfPopulation += Integer.parseInt(countryInfo.getStatePopulation().replaceAll(",", "")); } populations.put(countryInfo.getCountryCode(), sumOfPopulation); } return populations; }
问题:尝试返回按唯一国家代码分组的人口总和Map,但当前返回的是所有值的累计总和,而非每个国家各自的总和。
示例错误输出:
{America: 4329392, Canada: 13025402}
正确结果应该是:
{America: 4329392, Canada: 8721010}
修正方案
问题核心是用了全局的sumOfPopulation变量累计所有国家人口,且HashSet的判断逻辑完全多余,每个国家的人口总和需要单独维护。以下两种方式可解决:
方式1:手动遍历处理
直接用返回的Map维护每个国家的累计值,无需额外变量:
public HashMap<String, Integer> getAllCountryPopulations(){ List<CountryInfo> countries = countrySqlRepository.findAll(); HashMap<String, Integer> populations = new HashMap<>(); for(CountryInfo countryInfo : countries){ String countryCode = countryInfo.getCountryCode(); Integer statePop = Integer.parseInt(countryInfo.getStatePopulation().replaceAll(",", "")); // 已有该国家代码则累加,无则初始化 if(populations.containsKey(countryCode)){ populations.put(countryCode, populations.get(countryCode) + statePop); } else { populations.put(countryCode, statePop); } } return populations; }
方式2:Stream API简化实现(Java 8+)
用Stream的分组聚合功能,代码更简洁:
public Map<String, Integer> getAllCountryPopulations(){ return countrySqlRepository.findAll().stream() .collect(Collectors.groupingBy( CountryInfo::getCountryCode, Collectors.summingInt(info -> Integer.parseInt(info.getStatePopulation().replaceAll(",", "")) ) )); }
说明
- 方式1中,每个国家代码的总和存在Map对应value里,遍历到同国家的州就累加,确保每个国家总和独立计算。
- 方式2通过
groupingBy按国家代码分组,summingInt自动对每组州人口求和,避免手动遍历的逻辑错误。
内容的提问来源于stack exchange,提问作者koala421
相关产品推荐
相关产品推荐

