A Couple of Handy Apex Shortcuts

I came across a couple of handy Apex shortcuts in my Salesforce work this week.

In my Salesforce work this week I came across a couple of handy shortcuts in Apex:

Map a Record Collection to Map<Id,sObject>

A lot of Apex code seems to be making maps of objects to Ids for looking up later. The Map class has a Map<Id,sObject>(recordList) constructor that makes it quick and easy to convert a collection of records to a map of those records keyed by their Id.

// Get a collection of Contact records.
List<Contact> contacts = [SELECT Id, Name FROM Contact LIMIT 100];
// Create a map of Contact records keyed by their Id.
Map<Id,Contact> contactMap = new Map<Id,Contact>(contacts);

Documentation for “Map Class: Map Constructors: Map(recordList)”:

Creates a new instance of the Map class and populates it with the passed-in list of sObject records. The keys are populated with the sObject IDs and the values are the sObjects.

Binding a Record Collection in a SOQL WHERE IN Query

You can filter a SOQL query by a collection of Ids, but you can also use a collection of records to filter by their Ids.

// Get a collection of Account records.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 100];
// Get a collection of Contact records that belong to those Accounts.
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId IN :accounts];

Documentation for “Using Apex Variables in SOQL and SOSL Queries”. Note the comment in the example code:

An IN-bind with an Id list. Note that a list of sObjects can also be used--the Ids of the objects are used for the bind