How to Efficiently Save Data From SOQL Queries
One of the ways to write more efficient code in Apex is to use variables of the collections types to hold the results of SOQL queries. These queries return results of type List, but, as the title of this post suggests, it's not the most efficient method to store these results. Instead, it's preferable to use a collection of type Map. The reason for this is that while a collection of type List will hold a list of records for us, a collection of type Map will allow us to extract both a list of records and a list of IDs of the records using the Map.values() and Map.keySet() methods.
Example
Let's assume we want to run a query that will return all users in the system:
SELECT Id, Name FROM User
One option available to us is to store the results in a List in the following way:
List<User> allUsers = [SELECT Id, Name FROM User];
Now we have a list of all users in the system.
The second option is to store the results in a Map in the following way:
Map<Id, User> allUsers = new Map<Id, User>([SELECT Id, Name FROM User]);
Now we have three collections as follows:
- A map of all our users, mapped by ID: the variable allUsers.
- A set of all the IDs of our users: allUsers.keySet().
- A list of all our users: allUsers.values().
As you can see, using a map instead of a list provides us with much greater flexibility and essentially provides us with three variables for the price of one, without the need for loops to create a set of IDs or a list of records separately.