-2

I need to be able to add the values from two different maps with the same key. Is this doable?

Example Map 1:A =>10; B=>2; C=>3

Example Map 2:A =>1; B=>6; C=>4

Example Map 3:A =>11; B=>8; C=>7

1
  • 1
    Yes, it's doable (with a loop). Questions that can be answered with a simple yes/no aren't a great fit for this site. Please read How to Ask, and then edit your question to show us what you've tried so far.
    – Derek F
    Jan 10 at 19:09
0

Yes this is possible. The one decision that needs to be made is how to handle maps with different key sets. My example method below acts only on the intersection of the sets (meaning it iterates over only keys that are shared across both sets). If you have situations where the keys are different, the method would need to be adjusted to accommodate that. But as far as I'm concerned, adding null is undefined behavior.

public static Map<String, Integer> sumMaps(Map<String, Integer> m1, Map<String, Integer> m2) {
    Set<String> keys1 = m1.keySet();
    Set<String> keys2 = m2.keySet();
    // sets keys1 to the intersection of keys1 _and_ keys2 so that only shared keys are used
    keys1.retainAll(keys2);
    Map<String, Integer> summedMap = new Map<String, Integer>();

    for(String k : keys1) {
        summedMap.put(k, m1.get(k) + m2.get(k));
    }

    return summedMap;
}

Example:

Map<String, Integer> m1 = new Map<String, Integer>{
    'A' => 10, 'B' => 2, 'C' => 3
};
Map<String, Integer> m2 = new Map<String, Integer>{
    'A' => 1, 'B' => 6, 'C' => 4, 'D' => 55
};
Map<String, Integer> summedMap = sumMaps(m1, m2);
System.debug('summedMap = ' + summedMap);

// outputs "summedMap = {A=11, B=8, C=7}", note that the D value of 55 in m2 is omitted
10
  • Oh wow! I would only like to add keys that are similar across all both maps. Here is what I have so far.i.quoteCurrencyTotal.put(quote_currency + '' + price_unit, opportunity_line_item.Unit_Price_Quote_Currency__c !=null ? opportunity_line_item.Unit_Price_Quote_Currency__c: null); i.costCurrencyTotal.put(cost_currency + '' + price_unit, opportunity_line_item.Unit_Price__c !=null ? opportunity_line_item.Unit_Price__c: null); Jan 10 at 19:31
  • So I created the maps with the same appended keys, but I am not sure how to calculate the values Jan 10 at 19:35
  • If you only care about keys that are the same across maps, then my method will accomplish that. Look at Set.retainAll()
    – nbrown
    Jan 10 at 19:39
  • Thanks! I am just receiving alot of Unexpected token 'public' errors now. Any idea how to fix them? The code is too long to share Jan 10 at 20:22
  • I would ask a separate question
    – nbrown
    Jan 10 at 20:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.