Salesforce Collections – Maps

Maps are pretty useful and can make your code more readable and efficient. In particular, maps can be instantiated in a number of ways.

Here is the standard way of instantiating a map:

Map<Id, Account> accountsById = new Map<Id, Account>();

However, if you happen to have a list of sObjects you can just pass that list in the constructor like this:

Map<Id, Account> accountsById = new Map<Id, Account>([SELECT Id, Name FROM Account LIMIT 10]);

It is easy to work with Maps in Triggers

As you can see, no loops were needed to get a set of account ids. We simply passed the list of accounts to the new map instance and then used the maps keySet() method to get a list of ids for us.

Map<Id, Account> accountsById = new Map<Id, Account>(trigger.new);
Set accountIds = accountsById.keySet();
List contacts = [SELECT Id, FirstName, LastName FROM Contact WHERE AccountId IN :accountIds];

If you have a list of sObjects you don’t have to loop through and get a set of ids. You could just pass that list of sObjects to your query like this (assuming you have a list of account records in a variable called List accounts.

[SELECT Id FROM Contact WHERE AccountId IN :accounts]

Apex is smart enough to know how to get the account ids from the list and to apply them as part of the WHERE clause.

Permanent link to this article: https://salesforcebuddy.com/2019/01/salesforce-collections-maps/

Leave a Reply

Your email address will not be published.