125

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?

2 Answers 2

188

I know only one:

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

Here is the doc: Maps of sObjects

8
  • 3
    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. Dec 11, 2012 at 18:01
  • 4
    This is one to commit to memory. I use it all the time. Dec 11, 2012 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(); Dec 11, 2012 at 19:15
  • 15
    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); } May 4, 2015 at 15:13
  • @mast0r link is again changed :)
    – C0DEPirate
    Sep 16, 2015 at 7:13
64

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.

1
  • 1
    that is a good tip.
    – SeanW
    Aug 6, 2021 at 18:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .