java - 如何通过多个HashMap进行算术运算?

标签 java android collections

目前我有6个HashMap,其中包含城市名称和不同类别的值,但我需要总结每个类别的每个城市的值,即:

HashMap<String, Integer> HeatHMap = new HashMap<>();
HashMap<String, Integer> DaylightHMap = new HashMap<>();
HashMap<String, Integer> PrecitipationHMap = new HashMap<>();
HashMap<String, Integer> DaylightHMap = new HashMap<>();
HashMap<String, Integer> WindHMap = new HashMap<>();
HashMap<String, Integer> MoistureHMap = new HashMap<>();

其中 HeatHMap 包含:

Cities    Values
Tucson     23
Hermosillo 47
Boulder    25

DaylightHMap 包含:

Cities    Values
Tucson     43
Hermosillo 37
Boulder    75

现在,我需要将每个类别的每个城市(即埃莫西约)的值相加,并将这些值保存到另一个 HashMap 中,因此结果将类似于:

 Cities    Values
 Tucson      78 =  (23+43+...+n)
 Hermosillo  160 = (47+37+...+n)
 ....

我正在考虑将每个 HashMap 添加到 ArrayList 中,然后访问每个城市,但我意识到将 HashMap 放入列表中并不是解决这个问题的好方法。到目前为止,我已经:

public void verifyTheWinner(
HashMap <String, Integer> Table1, HashMap <String, Integer> Table2, 
HashMap <String, Integer> Table3, HashMap <String, Integer> Table4, 
HashMap <String, Integer> Table5, HashMap <String, Integer> Table6)
  {
    List<HashMap> categories = new ArrayList<HashMap>();

    categories.add(Weather);
    categories.add(SeaWeather);
    categories.add(Rainfall);
    categories.add(Sunshine);
    categories.add(Prices);
    categories.add(AvgStd);


    HashMap<String, Integer> citiesAndValuesTotal= new HashMap<>();

    for (int i=0; i<categories.size(); i++){
       ......
    }}

我的问题是:

  1. 如何执行算术运算,例如将每个城市的值相加,然后将它们保存到新的 HashMap 中?

  2. 是否有其他 Collection 可以用来实现此目标,或者 HashMap 是解决此问题的最佳方法吗?

感谢您的支持,如有需要请向我询问更多详情。欢迎每个答案。

最佳答案

使用更好的数据结构会更好,例如包含任何给定城市的所有所需详细信息的类:

public class CityWeather {
    private String name;
    private int heat;
    private int daylight;
    // ...
    private int moisture;
    // ...
}

那么你只需要一张 map ,比如说

HashMap<String, CityWeather> weatherMap = new HashMap<>();

该 map 可以满足您目前所有其他 map 所服务的需求,包括您要创建的 citiesAndValuesTotal map 。最后,您需要做的就是向 CityWeather 添加一个方法,如下所示:

int meaninglessWeatherSum() {
    return heat + daylight + ... + moisture;
}

然后您无需执行任何特殊操作即可执行计算 - 只要您需要,它就在那里。

关于java - 如何通过多个HashMap进行算术运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40897396/

相关文章:

c# - 将通用字典作为参数传递给需要 IDictionary 的方法是否可以

jsp - 使用 JSTL 检查集合大小

java如何从某些对象的列表中提取某些属性并且也易于重构

java - 迭代 <f :verbatim> within <ui:repeat>

java - 从头开始构建 Eclipse IDE - 如何指定目标操作系统?

android - 使用 picasso 加载图像时淡入动画

Android UI 在 View setRotation 上变慢

android - 在测试项目中使用资源文件夹获取测试字符串数据

java - SwingWorker 和 JProgressBar 的问题

c# - 集合 - 列表