How can I do it if I want to run a SOQL Query and get a Map returned?

376    Asked by AshishSinha in Salesforce , Asked on Sep 11, 2023

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

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

Is it possible to get Soql to map where OpportunityID would be the key and the value of the Opportunity? If there is none, please tell me the quickest way to convert to a map. 

Answered by bhagwati dubey

Only one way is known by me:

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

Here is the link to the doc: Maps of sObjects On the other hand, if you have a list already, for instance, let's say you are in a situation where you need a map, but you don't feel like refactoring your entire class to handle a map, then you can convert your list of result into a map like this:

  Map mapFromList = new Map(List_object_variable);

This will generate a map for you as if you have directly queried into a map.



Your Answer

Interviews

Parent Categories