[SalesForce] How to iterate over Map with same key, but different values

I have this map:

for(Opportunity opp: [Select Id, AccountId From Opportunity Where Id IN :SetIds]){
      mapAcctOpp.put(opp.AccountId, opp.Id);
}

When I try to iterate over this map like this:

Map<Id, String> toSave = new Map<Id, String>();

for(Account tempAct: [Select Id, Field__c from Account Where Id IN : mapAcctOpp.keySet()]){
    toSave.put(mapAcctOpp.get(tempAct.Id), Field__c);
}

My toSave map is unable to capture all the OppIds when I have same Account. I am not sure how to loop over the keys and values and have it work for both scenarios: Unique Account Ids and different Account Ids.

Best Answer

One of the approaches could be to use Map<Id, Set<Id>> structure in order to collect all data.

Consider following example:

Map<Id, Set<Id>> opportunity_ids_by_account_ids = new Map<Id, Set<Id>>();
for(Opportunity opp: [Select Id, AccountId From Opportunity Where Id IN :SetIds]){
      if (!opportunity_ids_by_account_ids.containsKey(opp.AccountId)) {
          opportunity_ids_by_account_ids.put(opp.AccountId, new Set<Id>());
      }
      opportunity_ids_by_account_ids.get(opp.AccountId).add(opp.Id);
}

In that case, per each account id, there would be set of opportunity ids, so that can be utilized in following way:

Map<Id, String> toSave = new Map<Id, String>();

for(Account acc: [Select Id, Field__c from Account Where Id IN : mapAcctOpp.keySet()]){
    if(opportunity_ids_by_account_ids.containsKey(acc.Id)){
        for(Id opp_id : opportunity_ids_by_account_ids.get(acc.Id)) {
             toSave.put(opp_id, acc.Field__c);
        }
    }
}
Related Topic