Saturday, 20 July 2013

Fun With Maps In Apex

Maps are my favorite collection types .The Reason why its very essential to use Maps in apex  classes or triggers is it makes life simple for writing bulkified apex class or trigger .

Read more on Maps in below article from salesforce

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_maps.htm
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_map.htm

Apex we all know runs on an multitenant  architecture .The resources are shared and hence we have governor limits in apex .The advantages of proper usage of maps will help  to  reduce script statements,No of queries for a single context of class or trigger execution,avoiding query on a single object twice .

As a fresher to salesforce  we are unaware of various techniques that we can employ to reduce the script statements and reduce heap size of collection like Lists,Maps and Sets.

You can read some nice articles in developerforce and get familiar with some of common techniques which developers have discovered to deal with no of script statements and heap size issues

My favorite  recipes are as follows

http://developer.force.com/cookbook/recipe/using-sobject-constructors-to-save-script-statements
http://developer.force.com/cookbook/recipe/initialising-maps-from-queries

If you have been coding in apex from long time you might  have come across common use case that you need to aggregate collection of child records grouped by ParentId.

Something like say i will query on Contact Object and i am retrieving all contacts and I need a collection Map of Parent Id (AccountId) as Key and the collection of contacts related to AccountId .In short in apex language terms Map<AccountId,List<Contacts>>

Here is the code that i have included as an example on how to form the collection of Map<Id,List<Contact>>



Hope you enjoyed the technique .Happy coding !Let me know the feedback on the Post.

4 comments:

  1. Thanks for this post Mohit.
    Please clarify following:
    Row no-12:mapAccIdByCntlst.put(c.AccountId, c);

    will this be : mapAccIdByCntlst.put(c.AccountId, lstcnts); ??

    ReplyDelete
    Replies
    1. Hi Thanks for that !Yes its mapAccIdByCntlst.put(c.AccountId, lstcnts) .I am updating the code

      Delete
  2. I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. click here

    ReplyDelete
  3. In line 8 mapAccIdByCntlst.get(c.AccountId).add(c); u said here map.get(key) is returning list and we are adding contacts to the list
    can u explain it !
    It is getting cont's accountid and contact is added.

    ReplyDelete

Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...