[英]How to calculate the sum of values of different hashmaps with the same key?
So I have this hashmap named "hm" which produces the following output(NOTE: this is just a selection) : 所以我有一个名为“ 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}
This output was created with the following code(NOTE : the rest of the class code is not shown here) : 此输出是使用以下代码创建的(注意:此处未显示类代码的其余部分):
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);
What I am trying to do is put all these hashmaps together into one hashmap with as value the sum of the values per key. 我正在尝试将所有这些哈希图放到一个哈希图中,并将每个键的值之和作为值。 I am familiar with Python's defaultdict, but could not find an equivalent working example.
我熟悉Python的defaultdict,但找不到等效的工作示例。 I have searched for an answer and hit those answers below but they do not solve my problem.
我已经搜索了一个答案并在下面打了这些答案,但是它们不能解决我的问题。
How to calculate a value for each key of a HashMap? 如何为HashMap的每个键计算值?
what java collection that provides multiple values for the same key 为同一键提供多个值的Java集合
is there a Java equivalent of Python's defaultdict? Java是否等效于Python的defaultdict?
The desired output would be : 所需的输出为:
{1=105, 2=156, 3=183 , 4=204 ,5=206 ..... and so on}
Eventually the average per position(key) has to be calculated but that is a problem I think I can fix on my own when I know how to do the above. 最终,必须计算每个位置(键)的平均值,但这是一个问题,我认为当我知道如何执行上述操作时,我可以自己解决此问题。
EDIT : The real output is much much bigger ! 编辑:实际输出要大得多! Think about 100+ of the hashmaps with more than 100 keys.
考虑具有100多个键的100多个哈希图。
Try with something like that 试试这样的东西
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;
}
Basically: 基本上:
newHashMap.put(key1,map1.get(key1)+map2.get(key1)+map3.get(key1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.