[英]how to merge more than one hashmaps also sum the values of same key in java
[英]How to calculate the sum of values of different hashmaps with the same key?
所以我有一個名為“ 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,但找不到等效的工作示例。 我已經搜索了一個答案並在下面打了這些答案,但是它們不能解決我的問題。
所需的輸出為:
{1=105, 2=156, 3=183 , 4=204 ,5=206 ..... and so on}
最終,必須計算每個位置(鍵)的平均值,但這是一個問題,我認為當我知道如何執行上述操作時,我可以自己解決此問題。
編輯:實際輸出要大得多! 考慮具有100多個鍵的100多個哈希圖。
試試這樣的東西
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;
}
基本上:
newHashMap.put(key1,map1.get(key1)+map2.get(key1)+map3.get(key1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.