Find your content:

Search form

You are here

Is it possible to run a SOQL Query and get a MAP returned?

 
Share

It is possible to run query and the results inserted into an Apex list:

List<Opportunity> opportunities = [SELECT Opportunity.OwnerId,
                                          Opportunity.Probability,  
                                          Owner.Name FROM Opportunity 
                                    WHERE Opportunity.LastModifiedDate = LAST_N_DAYS:7];

Is it possible to return a Map? Where the key would be the OpportunityID and the value the Opportunity?

If not, what is the quickest way to convert to a map?


Attribution to: dublintech

Possible Suggestion/Solution #1

I know only one:

Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);

Here is the doc: Maps of sObjects


Attribution to: Sergej Utko

Possible Suggestion/Solution #2

Alternatively, if you have a list already -- say you're in a situation where you need a map, but aren't in a mood to refactor your entire class to handle a map, you can convert your list of results to a map thusly:

Map<Id,OBJ_TYPE> mapFromList = new Map<Id,OBJ_TYPE>(List_object_variable);

This will generate a map from the list as if you'd queried directly into a map.


Attribution to: Kevin P
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/5288

My Block Status

My Block Content