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.

Introducing Lightning Base Components

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