I have a list of Account Ids with me. I want to convert it into Map. Is it possible to do that without using SOQL in loop to retrieve the Account object per ID? I need this to add it to my trigger and don't want to run in governor limits of SOQLs
1 Answer
This is a very common SOQL bulkification idiom.
Given some List<Id>
or Set<Id>
containing Account Ids, you can query directly into a Map<Id, Account>
by passing the query to the constructor of the Map
and using an Apex bind to include the collection in your query.
List<Id> myIds = ...;
Map<Id, Account> accountMap = new Map<Id, Account>(
[SELECT Id, Name, ... FROM Account WHERE Id IN :myIds]
);
This consumes exactly one SOQL query against limits, is efficient in creating the data structure, and makes it easier for your downstream code to consume the Accounts efficiently and without performing further queries.