« Salesforce Dataloader Heap Space Exception | Main | Three Common Apex Coding Topics »

Using An Apex Map with a List of sObjects

The other day I found this handy. It's a slight twist on something I found in the developer documentation. Ultimately I wanted to quickly compare some Account IDs and see if any from list A were in list B and if so, perform an action on the Accounts in list B. I decided that a map would be good for this task.

First, a quick review of what a Map is. A map is essential a key/value pair list. Here is the textbook definition:

A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. - Salesforce Developer Documentation

A Map is perfect for this particluar task because Salesforce object IDs are unique just like the key in a Map. There is only ever going to be one.  

Below is a snippet of an "auto" populated map of the Accounts I was interested in.


List<Account> listAccountsWithSupport = [select Id,Name from Account where HasPaidSupport__c =  true];
Map<Id, Account> mapAccountsWithSupport = new Map<Id, Account>(listAccountsWithSupport);

I can now quickly compare the Accounts I have in List A with this second set of Accounts stored in a map. Both A & B could actually be maps but the method I'm working with in the legacy code already returns a List for the Accounts in pile A.

for(Account a: listAccountA){

//check to see if the current account in list A matches any in our Map (which is pile B)

  if(mapAccountsWithSupport.containsKey(a.Id)) {

      a.HasPaidSupport__c = true; //perform the desired action

/*we can also perform actions on any of the accounts in the Map if we want by using a.Id to find a specifc Account. Below will return the actual Account object based on the  key "id" if it finds one. At this point you could perform an action if you wanted. */

     Account tmpAccount = m.get(a.Id);



update listAccountA; //make sure to call any updates outside the loop :)


PrintView Printer Friendly Version

EmailEmail Article to Friend

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.
  • Source
    Source: Maps

Reader Comments (1)

I might suggest updating the first portion of your code to:

Map<Id, Account> mapAccountsWithSupport = new Map<Id, Account>([select Id,Name from Account where HasPaidSupport__c = true]);

This will remove the need for a list altogether.
September 16, 2014 | Unregistered CommenterTyler Mowbrey

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
All HTML will be escaped. Hyperlinks will be created for URLs automatically.