【问题标题】:How to sum values in a map efficiently within java如何在java中有效地对地图中的值求和
【发布时间】:2022-08-17 00:27:24
【问题描述】:
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;
     }

我正在尝试返回给定地图上唯一国家代码的值的总和。我没有返回集合中每个键的相应总和,而是得到集合中所有值的总和。

我如何在这里修复我的逻辑?

提前致谢。

  • 你能澄清一下这个说法吗:Instead of returning the corresponding sum for each key in the set I am getting the sum of all values within the set
  • 最好提供CountryInfo类的代码和样本数据代表输入,电流输出期望的输出.

标签: java hashmap sum


【解决方案1】:

我相信使用计算方法在这里会有所帮助。

final List<CountryInfo> countries = countrySqlRepository.findAll();
        final HashMap<String, Integer> populations = new HashMap<>();
        for (final CountryInfo countryInfo : countries) {
            populations.compute(countryInfo.getCountryCode(), (k, v) -> {
                final int sum = Integer.parseInt(countryInfo.getStatePopulation().replaceAll(",", ""));
                return v == null ? 0 : v + sum;
            });
        }
        return populations;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多