【问题标题】:How to calculate the sum of values of different hashmaps with the same key?如何计算具有相同键的不同哈希图的值之和?
【发布时间】:2016-10-08 13:46:22
【问题描述】:

所以我有一个名为“hm”的哈希图,它产生以下输出(注意: 这只是一个选择):

{1=35, 2=52, 3=61, 4=68, 5=68, 6=70, 7=70, 8=70, 9=70, 10=72, 11=72}

{1=35, 2=52, 3=61, 4=68, 5=70, 6=70, 7=70, 8=68, 9=72, 10=72, 11=72}

{1=35, 2=52, 3=61, 4=68, 5=68, 6=70, 7=70, 8=70, 9=72, 10=72, 11=72}

此输出是使用以下代码创建的(注意:此处未显示其余的类代码):

private int scores;
HashMap<Integer,Integer> hm = new HashMap<>();

for (int i = 0; i < fileLines.length(); i++) {
    char character = fileLines.charAt(i);
    this.scores = character;
    int position = i +1;
    hm.put(position,this.scores);
 }
 System.out.println(hm);

我要做的是将所有这些哈希图放在一个哈希图中,并将每个键的值的总和作为值。我熟悉 Python 的 defaultdict,但找不到等效的工作示例。我已经搜索了答案并点击了下面的答案,但它们并没有解决我的问题。

How to calculate a value for each key of a HashMap?

what java collection that provides multiple values for the same key

is there a Java equivalent of Python's defaultdict?

期望的输出是:

{1=105, 2=156, 3=183 , 4=204 ,5=206 ..... and so on}

最终必须计算每个位置(键)的平均值,但我认为当我知道如何执行上述操作时,我可以自己解决这个问题。

编辑:实际输出要大得多!想想 100 多个具有超过 100 个键的哈希图。

【问题讨论】:

  • 是什么阻止您遍历所有 3 个 HashMap 的条目并对每个键的值求和?
  • 如果您知道键是 1 到 11,只需 for 循环并使用 get() 求和。如果您不知道键,但知道所有映射具有完全相同的键,只需从其中一个中迭代键,然后使用 get() 求和。
  • 谢谢你,我会试试你的建议!

标签: java hashmap


【解决方案1】:

试试类似的东西

public Map<Integer, Integer> combine(List<Map<Integer, Integer>> maps) {
    Map<Integer, Integer> result = new HashMap<Integer, Integer>();
    for (Map<Integer, Integer> map : maps) {
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int newValue = entry.getValue();
            Integer existingValue = result.get(entry.getKey());
            if (existingValue != null) {
                 newValue = newValue + existingValue;
            }
            result.put(entry.getKey(),  newValue);
        }
    }
    return result;
}

基本上:

  • 为结果创建新地图
  • 遍历每张地图
  • 获取每个元素,如果结果中已经存在则增加值,如果没有将其放入地图中
  • 返回结果

【讨论】:

  • 感谢您的清晰解释!我绝对可以用这个例子做点什么!
【解决方案2】:
   newHashMap.put(key1,map1.get(key1)+map2.get(key1)+map3.get(key1));

【讨论】:

  • 但是如果我有 100 个哈希图呢?这里就是这种情况,这只是一小部分输出的示例。
  • 我只是举个例子,你可以这样做,你应该写循环。
  • @nikeshjoshi 我的观点只是关于如何选择变量的名称,key1 似乎你只在第一个地图上循环。如果您循环遍历所有三个映射键,则它可以工作(如果您不在同一个键上循环两次)。我没有投反对票
猜你喜欢
  • 2011-10-04
  • 2018-11-13
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2014-09-14
  • 2011-03-10
相关资源
最近更新 更多