+ Start a Discussion
Kenji775Kenji775 

Dumb syntax question

Hey all,

 

Say I have a map of Ids, and lists. Like so

 

Map<Id, List<Id>> CampaignAccountIdMap = new Map<Id, List<Id>>();

 

Then I want to populate map with data from a query.

 

         for (Respondent__c r :[select Id,
                                                   Respondent__r.AccountID,
                                                  Master_Campaign__c
                                                  From Respondent__c
                                                  Where Master_Campaign__c in :CampaignIds])
        {
            CampaignAccountIdMap.put(r.Master_Campaign__c,r.Respondent__r.AccountID);
        }   

 

Normally to add something to a list it would be listname.add(value)

but a list contained within the map doesn't really have a name? How would I populate my CampaignAccountIdMap with the id's of the campaign, and a list of account IDs?

joshbirkjoshbirk

does CampaignAccountIdMap.get( [CampaignId] ).add( [AccountId] ) work?

DharmeshDharmesh

you can do some thing like this

 

 for (Respondent__c r :[select Id,
                                                   Respondent__r.AccountID, 
                                                  Master_Campaign__c
                                                  From Respondent__c
                                                  Where Master_Campaign__c in :CampaignIds])
        {
            CampaignAccountIdMap.put(r.Master_Campaign__c,new List<Id>{r.Respondent__r.AccountID});
        } 

bob_buzzardbob_buzzard

In the event of more than one value for the same key, this will overwrite the existing list in the map with a new instance.

 

Normally you'd pull the list out of the map, if its null instantiate a new one, and then add the value to the list.

 

E.g.

 

 

for (Respondent__c r :[select Id,
                       Respondent__r.AccountID, 
                       Master_Campaign__c
                       From Respondent__c
                        Where Master_Campaign__c in :CampaignIds])
{
   List<Id> theList=CampaignAccountIdMap.get(r.Master_Campaign__c);
   if (null==thelist)
   {
      theList=new List<Id>();
      CampaignAccountIdMap.put(r.Master_Campaign__c, theList);
   }
   theList.add(r.Respondent__r.AccountId);                    
}