1

Is it possible to increment a map decimal value in a loop based on a sObject field? I have a map and for each unique SKU, I would like to increment the decimal based on a field called Reporting_Sales__c as I loop through my superSummaries list.

I have tried multiple methods but the map is only retaining the last value. I am trying to avoid putting the SKUs in a set, as collection sizes get pretty large.

Any help would be greatly appreciated - thank you!


        decimal bsTotalSales = 0;

        // Map of SKUs and their respective total sales
        Map<string,decimal> skuSalesMap = new Map<string,decimal>();

        for(Super_Summary__c ss : superSummaries){
            if(ss.Budget_Summary__c == bs.id){

                bsTotalSales += ss.Reporting_Sales__c;

                skuSalesMap.put(ss.SKU__c,0);                   
                skuSalesMap.put(ss.SKU__c,skuSalesMap.get(ss.SKU__c) + ss.Reporting_Sales__c);

                system.debug('skuSalesMap Reporting Sales = ' + skuSalesMap.get(ss.SKU__c)); 
            }
        }

2

This will fix your problem:

       decimal bsTotalSales = 0;

        // Map of SKUs and their respective total sales
        Map<string,decimal> skuSalesMap = new Map<string,decimal>();

        for(Super_Summary__c ss : superSummaries){
            if(ss.Budget_Summary__c == bs.id){

                bsTotalSales += ss.Reporting_Sales__c;

                if (! skuSalesMap.containsKey(ss.SKU__c)) {
                  skuSalesMap.put(ss.SKU__c,0);                   
                }

                skuSalesMap.put(ss.SKU__c,skuSalesMap.get(ss.SKU__c) + ss.Reporting_Sales__c);

                system.debug('skuSalesMap Reporting Sales = ' + skuSalesMap.get(ss.SKU__c)); 
            }
        }

You have to make sure you only initialize the counter once. In your previous version of the code, you were doing it every time you went through the loop... obviously, that's only going to leave the last value there.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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