Saturday 18 May 2013

Master in Salesforce Apex collection

Before starting collection ,My first question is what is the meaning of collection? Why collection came to picture ?
Collection is nothing but a group of elements.So Now my question  is,  how can we handle a group of elements?  Ok we can handle a group of elements with help of array.My next question is Can we handle a group of objects with the help of array ? yes we can ,but still why we need collection ? What are the inconveniences  for which we need collection?
Below are the drawback with array for which we need collections.
1.We can not store different class objects into the same array, reason is that array can store a single data type.
2.We can add an element to the end of the array.But inserting and deleting  an element to the middle of the array is difficult.
3.We can retrieve the elements from the array but there is no such methods to process the elements.

Due to such problems  developers wants an object to store a group of  objects .Such an object is nothing but collection.

For a java developer apex collection is very simple, because java collection frame work  has a lot of classes,abstract classes and also interfaces.

Sales force Apex  has  only three types of  collections.
1.List :-
    List is an ordered collection of primitive,sObjects,userdefind objects,apex objects or collection that are distinguished by indexes.We can add duplicate element in the list.
List are index-based so the index position of first element in a list is always zero(0).
List can have upto five level of nested collection inside it.
2 . Set :-
      A set represents a group of  elements arranged just like an array. Set will grow dynamically    when the elements are stored into it .  Set elements can be of any data type—primitive , collections, sObjects, user-defined types, and built-in Apex types.Set will not allow duplicate elements.

3.Map:-
       A map is a collection of key-value pairs ,where key should be  unique and value can be duplicate . Each unique key maps to a single value.Through the key we can retrieve values.  
Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. 

Note : There is no such  limit on the number of items a collection can hold. How ever there is a general limit on  heap size.

All collection in apex are ordered from 34 version on wards .

Lets play with the methods of different collection.

List class have some methods ,just click on the link   list methods    to  refer  all list methods .

Set class have some methods ,just click on the link   set methods    to  refer  all Set methods .

Map class have some methods ,just click on the link   Map methods    to  refer  all map methods .


I think now we are familiar with all methods in above three classes .
Lets discuss one real time scenario where we can implement collection to over come the limits .

Here is one scenario like when you will update any  account owner then related contact owner should update with same value

Below is the trigger code which can write in Account and test it will work ,however in case of mass update it will give you error .

1.101 SOQL error because contact query is inside the for loop .
2.Too many  DML rows: 10001 .

Trigger updateownerofcontact on Account(before update) {
 for(Account currentAccount : trigger.new) {
  if(currentAccount.OwnerId != Trigger.oldMap.get(currentAccount.Id).OwnerId){
   for(Contact con: [SELECT Id, OwnerId, AccountId FROM Contact
                     WHERE  AccountId = :currentAccount ]) {
    con.OwnerId=currentAccount.OwnerId;
    update con;
   }
  }
 }
}
 
To avoid this we need to use collection ,check below code where collection
used to avoid all above error .
Here we need to remove contact query and update statement to out of for  loop 
  
Trigger UpdateOwnerOfContact on Account(before update) {
 //Map to collect account id with changed owner id(user id ) .
 Map<Id,Id> accIdWithOwnerIdMap = new Map<Id,Id>();
 List<Contact> listOfContactsToUpdate = new List<Contact>();
 for(Account currentAccount : trigger.new) {
     if(currentAccount.OwnerId != Trigger.oldMap.get(currentAccount.Id).OwnerId){
        accIdWithOwnerIdMap.put(currentAccount.Id,currentAccount.OwnerId);
     }         
 }
 if(!accIdWithOwnerIdMap.isEmpty()){
  for(Contact con: [SELECT Id, OwnerId, AccountId FROM Contact 
                    WHERE AccountId IN :accIdWithOwnerIdMap.keySet() ]) {
   con.OwnerId = accIdWithOwnerIdMap.get(con.AccountId);
   listOfContactsToUpdate.add(con);
  }
 }
 if(!listOfContactsToUpdate.isEmpty()) {
  try{
   update listOfContactsToUpdate;
  }catch(DmlException de){
   System.debug(de);
  }
  
 }




No comments:

Post a Comment