0

Could anyone help me with the code bellow please? MasterIdSet - may contain one or more ids Master_ID__c - is an external id which value could be the same across one or more Accounts. I would expect to see 2 Account records in my map, because the Master_ID__c is populated to two accounts:

acctMap{144383353=(001G000006iXPV3AAO), (001G000004iXPV3AAO)}

but getting:

acctMap{144383353=(001G000006iXPV3AAO)}

Here is my code:

 Set<String> masterIdSet = new Set<String>();
    Map<String,list<id>> acctMap = new Map<String,list<id>>();
    for(Account a:[SELECT Id, Owner.Id, Owner.Name, Salesforce_Account_ID__c, Name, Status__c,Include_in_Funnel__c, Master_ID__c FROM Account WHERE Master_ID__c IN :masterIdSet]) acctMap.put(a.Master_ID__c, new list<id>{a.Id});
    System.debug('acctMap' +acctMap);
2

Map have unique keys, even if you have same key in loop , the latest key will overwrite the value of the old key. You have to check if key exists, if yes add Id to the list else create a new list for the key.

Set<String> masterIdSet = new Set<String>();
Map<String,list<id>> acctMap = new Map<String,list<id>>();
for(Account a:[SELECT Id, Owner.Id, Owner.Name, Salesforce_Account_ID__c, Name, Status__c,
                Include_in_Funnel__c, Master_ID__c 
                FROM Account 
                WHERE Master_ID__c IN :masterIdSet]){

        if(acctMap.containsKey(a.Master_ID__c)){
            acctMap.get(a.Master_ID__c).add(a.Id);
        }else{
            acctMap.put(a.Master_ID__c, new list<id>{a.Id});
        }

}
System.debug('acctMap' +acctMap);
| improve this answer | |
0

You keep replacing the list with a new list every time

You need to see if a value exists, if it does add to it and replace the old value.

Set<String> masterIdSet = new Set<String>();
Map<String,list<id>> acctMap = new Map<String,list<id>>();
for(Account a:[SELECT Id, Owner.Id, Owner.Name, Salesforce_Account_ID__c, Name, Status__c,Include_in_Funnel__c, Master_ID__c FROM Account WHERE Master_ID__c IN :masterIdSet]) {
    List<Id> existingList = acctMap.get(a.Master_Id__c);
    if (existingList == null) {
        existingList = new List<Id>;
    }
    existingList.add(a.Id);
    acctMap.put(a.Master_ID__c, existingList);
}

System.debug('acctMap' +acctMap);
| 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.