Salesforce: Automatically Creating an Apex Map from a List with ID of SObject as the Key

I recently learned something that is already saving me a ton of time.  I didn’t know it was possible to take a list of SObjects, and create a Map<Id, SObject> without writing an explicit loop to traverse the list.  But, Apex developers, we can do just that with the following map constructor:

Map<Id, SObject>(List<SObject>)

So, let’s say I’d queried up a list of Account records, as so:

List<Account> myAccountList = [ SELECT Name, AccountNumber FROM Account LIMIT 50 ];

What I had been doing previously to create a Map<Id, SObject> was this:

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

for(Account a : myAccountList) {
     myAccountMap.put(a.Id, a);
}

Granted, that works.  But, how much EASIER is this?

Map<Id, Account> myAccountMap = new Map<Id, Account>(MyAccountList);

You can read more about this in the Salesforce documentation on the Apex map class, specifically here.

I also think I read something about the idea in Dan Appleman’s book, “Advanced Apex Programming for Salesforce.com and Force.com..”  If you want to be a better Apex programmer, pick up a copy of that book.  There on links on the book’s website for purchasing a copy.

One thought on “Salesforce: Automatically Creating an Apex Map from a List with ID of SObject as the Key”

  1. Thanks for your post! The similar thing that I also recently learned:
    A *key* thing about the more indirect method is that you can re-set
    the field being used for the Map key, as in:

    for(Account a : myAccountList) {
    myAccountMap.put(a.ContactId, a);

    so when you want to retrieve the values from the map diferently.

Leave a comment