0

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.

  • You cannot have same key added in a Map with different values. Keys are always unique, the time you add another key with same value, the older gets overridden. Are you saying your key can contain multiple values, in this case multiple Opportunity Ids, and that's what you want to retrieve? – Jayant Das Oct 7 '19 at 20:33
  • You might use map of list by id structure: Map<Id, List<Id>> opp_ids_by_account_id;. In that case you can write for(Id opp_id : opp_ids_by_account_id.get(some_account_id)) { /*code*/} – kurunve Oct 7 '19 at 21:33
  • 3
    see salesforce.stackexchange.com/a/275079/2602 for a way to do this pattern over and over again – cropredy Oct 7 '19 at 21:46
3

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);
        }
    }
}
  • Awesome. I need to learn these data structures. Can you please post a resource where I can learn more about these? Like where can I learn when/how to use, Map<Id, Set<Id>>() and others for specific use-cases? – Austin Evans Oct 8 '19 at 17:25
0
  1. create a map of opportunity id as a key and set of opportunity ids i.e : Map<Id, Set<Id>>
  2. Use that map keys(accountids) in SOQL
  3. Create a map which is store field values with opportunityid i.e Map<Id,String> for your third soql

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.