[英]Multiplying Values of Two HashMaps
如果我有兩個HashMap
, hm1
和hm2
,我如何遍歷這兩個並在兩個HashMap
的每個點將兩個值相乘並求和? 它們的順序相同,所以我不需要擔心鍵,只需擔心值。
數據在表格中
hm1 =
(A, 3)
(B, 4)
(C, 7)
hm2 =
(A, 4)
(B, 6)
(C, 3)
然后我想做這樣的事情,但顯然這段代碼是不正確的,因為我只是在遍歷 hm1。
double sum = 0.00;
for (Map.Entry<String, Double> hm : hm1.entrySet()) {
sum += hm1.getValue() * hm2.getValue();
}
所以我基本上會循環並做:
1st iteration: Sum = 0 + 3*4
2nd Iteration: Sum = 12 + 4*6
3rd iteration: Sum = 36 + 7*3
Exit Loop:
Sum = 57
感謝你給與我的幫助。
假設兩個HashMap的條目數相等,並且所有條目具有相同的對應鍵,則獲取總和的可靠方法如下所示:
double sum = 0;
/* iterate through all the keys in hm1 */
/* order doesn't matter */
for (String key : hm1.keySet()) {
double value1 = hm1.get(key);
double value2 = hm2.get(key);
sum += value1 * value2;
}
您可以在第一個地圖上使用迭代中的鍵來獲取第二個地圖的值:
double sum = 0.00;
for (Map.Entry<String, Double> hm : hm1.entrySet()) {
double hm2Value = hm2.get(hm.getKey());
sum += hm.getValue() * hm2Value;
}
請注意,這僅在兩個地圖具有相同的鍵時才有效。 如果兩者都不存在,則必須考慮如何處理。
Java 版本 8,您可以使用 Stream API:
Map<String, Double> hm1 = new HashMap<String, Double>() {{
put("A", 3.0);
put("B", 4.0);
put("C", 7.0);
}};
Map<String, Double> hm2 = new HashMap<String, Double>() {{
put("A", 4.0);
put("B", 6.0);
put("C", 3.0);
}};
double sum = hm1.entrySet()
.stream()
.filter(entry -> hm2.containsKey(entry.getKey()))
.map(entry -> entry.getValue() * hm2.get(entry.getKey()))
.mapToDouble(value -> value)
.sum();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.