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

  • 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?

  • Sergej Utko

    Sergej Utko Correct answer

    9 years ago

    I know only one:

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

    Here is the doc: Maps of sObjects

    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.

    This is one to commit to memory. I use it all the time.

    Also, a quick way to get a set of returned Ids from a query is similar.. using the above code, just do Set myIds = m.keySet();

    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 oppList = [Select Id, AccountId from Opportunity]; Map accOppMap = new Map(); for(Opportunity o : oppList){ accOppMap.put(o.AccountId,o); }`

    @mast0r link is again changed :)

    any option to use it with child query like this.? Map> m = new Map>([SELECT Id (SELECT Id FROM Contacts) FROM Account]);

    I was getting this result can you clarify why i'm getting isocurrecyfireld here this is my Query--> map acc = new map([select id,name,CreatedDate from account limit 10]); system.debug(acc); result--> 0016F00002THXyjQAH=Account:{Id=0016F00002THXyjQAH, Name=test1, CreatedDate=2018-09-03 12:33:32, CurrencyIsoCode=USD}

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used