Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 44 down vote accepted

I know only one:

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

Here is the doc: Maps of sObjects

share|improve this answer
2  
That's a much better way to do it. I updated your link since it was just taking me to the home page instead of the specific topic. –  Ryan Elkins Dec 11 '12 at 18:01
    
Yehh right, thanks :) –  mast0r Dec 11 '12 at 18:03
    
This is one to commit to memory. I use it all the time. –  Kevin O'Hara Dec 11 '12 at 18:47
2  
Also, a quick way to get a set of returned Ids from a query is similar.. using the above code, just do Set<Id> myIds = m.keySet(); –  James Loghry Dec 11 '12 at 19:15

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.