• Home
  • About
    • Leadership
    • Partners
    • Blogroll
  • Force-Squared Blog
    • Tips and Tricks
    • Configuration
    • Development
  • Support
    • Knowledge Base
    • Submit a Case
  • Is It Dreamforce Yet?

X-Squared On Demand

Salesforce solutions delivered

  • Home
  • About
    • Leadership
    • Partners
    • Blogroll
  • Force-Squared Blog
    • Tips and Tricks
    • Configuration
    • Development
  • Support
    • Knowledge Base
    • Submit a Case
  • Is It Dreamforce Yet?
  • Tips and Tricks
  • Configuration
  • Development
You are here: Home / Salesforce CRM / Development / Apex / Create and Populate a Map Without Loops

Create and Populate a Map Without Loops

July 25, 2012 by David Schach 7 Comments

There are many reasons to use Maps in Apex triggers. Sometimes I want to make a List of Contacts, but I want to pull each one by its ID. This is a good reason to abandon the List and to make a Map<Id, Contact>. (Some will prefer to use Map<String, Contact>, and that is okay too.) We could use a for loop, but let’s try something more efficient.

This is how I used to populate a Map<Id, Contact> of all Contacts at Accounts in a trigger:

Map<Id, Contact> cs = new Map<Id, Contact>();
for (Contact c : [SELECT id FROM Contact WHERE AccountId IN :trigger.newMap.keyset()]){
    cs.put(c.id, c);
}

This takes time and uses script statements, and in a big org/app, we want to minimize both.

Here’s my new way:

Map<Id, Contact> cs = new Map<Id, Contact>(
    [select Id FROM Contact WHERE AccountId IN :trigger.newMap.keyset()]
);

It’s pretty simple, and it works well. It also keeps code clean.

More astute readers will note that this is similar to the Trigger context variables Trigger.oldMap & Trigger.newMap, which populate a map of the trigger records keyed to their record ids.

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to email a link to a friend (Opens in new window) Email

Related

Filed Under: Apex, Tips and Tricks Tagged With: Apex, Force.com Platform

← Workflow ISCHANGED() translated to Apex trigger Chatter Publisher Actions (Part 1): Create a Record →

Comments

  1. Ryan says

    July 25, 2012 at 10:03

    Good catch. One thing to note that takes this one step further: the constructor for Map can always take a List, which is essentially what you are using in your new way.

    So this can be used anywhere. It can be especially useful when using dynamic soql and the Database.query() method, which returns a List, but when you want a map, like this:

    String query = ‘select Id, Name from Account’;
    Map accountsMap = new Map((List)Database.query(query));

    …(note that Database.query returns a List always, so it can be casted into the strongly-typed list of the type you want, which is what is happening here)

    It can also be especially useful when you need to make a map out of a child collection of an SObject, such as the “Contacts” collection of an Account record. For example, when you query an account with all of its contacts …

    Account a = [select Id, Name, (select Id, Name from Contacts) from Account limit 1];

    … since the “Contacts” collection is just a List, you can make a Map like this:

    Map contactsMap = new Map(a.Contacts);

    Reply
  2. Brian Kwong says

    August 6, 2012 at 07:30

    Does this assumes that the map you want is formatted as map with key being the ID of the sobject?

    IF I want a map where the id is a lookup value in the sobject, or a map with the string a text/number value in the sobject I would still need to create a loop. Am I correct with this assumption?

    Reply
    • David Schach says

      August 6, 2012 at 12:12

      Exactly, Brian. This puts the sfdcID as the key, and the sObject as the value. (A map is basically a list of key-value pairs where the keys are unique within the keyset.)
      Using any other field as the key requires a loop.

      Reply
  3. Brian Kwong says

    August 6, 2012 at 12:28

    Thanks David – although I was hoping I was wrong with my assuming and found a more awesome way to creating my maps!

    Reply
  4. Mariappan says

    August 6, 2013 at 22:19

    Hi.
    Its great to see the map concept without loops.
    My question is like : Is it possible to have map =[SOQL Query];
    I know its a kind of mad question but if it exist , we could reduce the loops as you did in this blog .
    Anyway thanks a lot in advance .

    Reply
    • David Schach says

      August 7, 2013 at 10:13

      That is close to what I did, but we have to differentiate between a Map and a List. There is a limitation (feature?) in Apex, as in Java or C++, where one must instantiate a new map before populating it.
      Apex does let you create a List without instantiating it, and that is what one would get from your query:
      List mylist = [SELECT Id, Name FROM Account];
      Bottom line: Maps must be instantiated with a “new” call. Lists are what one gets when not instantiating a Map. I hope this helps.

      Reply

Trackbacks

  1. Force.com Design Patterns: Populate a Map Without Using For Loops | Delivered Innovation Blog says:
    September 8, 2012 at 13:35

    […] Create and Populate a Map<Id, Sobject> Without Loops jQuery(document).ready(function($) { […]

    Reply

Share Your ThoughtsCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Is it Dreamforce Yet?

Find out!

Find us on the AppExchange

Mass Update Contacts 2.0

Get It Now

Recent Posts

  • Prevent Duplicate Emails on Leads
  • Duplicate Record Item Enrichment and Auto-Deletion Code
  • Lightning Component With Running User Information
  • ChatterBINGO is Now Open-Source
  • Display Only My Role’s Records on a Report

Post Categories

Popular Tags

#df09 #df10 Akismet Apex AppBuilder AppExchange Appirio Astadia Blogs Chatter Configuration Content DreamFactory Dreamforce Eclipse IDE Enterprise Force.com Builder Force.com Platform Google Infowelders Integration Just for fun Lightning New Developments New Features Partner Program PersonAccount Projects Publisher Salesforce Salesforce1 Salesforce for Google Apps sfdcverse Sites Visualforce Web-to X-Squared On Demand

Find Us Online

  • Twitter
  • Facebook
  • LinkedIn
  • RSS

Subscribe

RSS Feed Comments

Subscribe via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 164 other subscribers

Copyright © 2008–2025 X-Squared On Demand · Genesis Framework by StudioPress · WordPress · Log in