Populate Existing Map from SOQL Query

Every example of SOQL queries being used (the official documentation, for example) shows a new map being populated with the results of an SOQL query like this –

Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10])

I’d like to populate a map that’s been created outside of one method in my class, so that I can retrieve values from it in another method.

But when I try

Map<Id,ProjectxOpp__c> pxOs = [SELECT Id,Opportunity__r.Account.Name
                                 FROM ProjectxOpp__c
                                WHERE Opportunity__c IN :stage4EuOpps.keySet()];

I get an error

Illegal assignment from List to Map

I know that I could create a map in my method with the results of the query & then copy that map to the map outside my method but this seems like a waste of time.

Is it possible to populate an existing map from an SOQL query?

Answer

Try this, from the doc they say that putAll can take an sObjectArray (list of sObjects)

pxOs.putAll([SELECT Id,Opportunity__r.Account.Name
                                 FROM ProjectxOpp__c
                                WHERE Opportunity__c IN :stage4EuOpps.keySet()]);

Attribution
Source : Link , Question Author : Alex S , Answer Author : benahm

Leave a Comment