96

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?

139

I know only one:

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

Here is the doc: Maps of sObjects

  • 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
  • 3
    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
  • 7
    To clarify, this method can only be used to generate Maps using Id of the object you are querying as the key. If you want to use a different value as the key, you will have to iterate over the list returned by your query and put values into a Map. For instance, if you wanted to use AccountId as the key, you would need to do something like this: List<Opportunity> oppList = [Select Id, AccountId from Opportunity]; Map<Id,Opportunity> accOppMap = new Map<Id,Opportunity>(); for(Opportunity o : oppList){ accOppMap.put(o.AccountId,o); } – Todd Sprinkel May 4 '15 at 15:13
  • @mast0r link is again changed :) – C0DEPirate Sep 16 '15 at 7:13
50

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.

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.