簡體   English   中英

在兩個地圖中乘以相應值的最佳方法

[英]Best way to multiply corresponding values in two maps

如何將 map1 的值乘以它在 map2 中的對應值? 我嘗試了兩個 for 循環,但它遍歷了兩個地圖 16 次。 假設兩個映射將始終具有相同的長度。

Map<String, Integer> map1= new HashMap<>();
Map<String, Integer> map2= new HashMap<>();

map1.put("one", 1);
map1.put("two", 2);
map1.put("three", 3);
map1.put("four", 4);

map2.put("one", 1);
map2.put("two", 2);
map2.put("three", 3);
map2.put("four", 4);

//map1 = {(one, 1), (two, 2)... etc
//map2 = the same

for(Integer num:map1.values()){
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

我做錯了什么。 我想乘以每個值並得到那個總和,即 (1 * 1) + (2 * 2) ...

流式傳輸條目,將每個條目的值乘以其在另一個映射中的匹配值,然后求和:

int sum = map1.entrySet().stream()
  .mapToInt(e -> e.getValue() * map2.get(e.getKey()))
  .sum();

Java 映射中的鍵/值對是無序的。 不能保證當您迭代下面的值時,您將獲得相同順序的值。

for(Integer num:map1.values())[
    for(Integer num2:map1.values()){
        total = num * num2;}}
System.out.println(total);

以下將做到這一點

for (Map.Entry<String, Integer> entry : map1.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    total += value * map2.get(key);
}
System.out.println(total);

上面的代碼假設你總是在map2擁有來自map1的鍵! 其復雜度為 O(n)* O(1),其中 n 是map1的鍵數。 訪問map2的值被認為是常量。

您應該迭代一張地圖的鍵,從另一張地圖獲取相關值(可能使用getOrDefault為缺少的 ket 返回默認值)並計算它們的產品總數:

int total = 0;

for (String key : map1.keySet()) {
    total += map1.get(key) * map2.getOrDefault(key, 0);
}

使用 Stream API 的類似解決方案:

int total = map1.entrySet().stream()
    .mapToInt(e -> e.getValue() * map2.getOrDefault(e.getKey(), 0))
    .sum();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM