Collections In Salesforce
If you are new to salesforce you might be confusing more with Map in salesforce. Let's get clear on all types of collections in salesforce.
Variable :
Variable is a container which holds the single value when the code is executed.
Eg1 : String str
We can store single value (Of string Type) in the Str.
Eg2 :Account Acc;
Acc can hold one account record at a time.
But As Salesforce Developer it is best practice to follow bulkification instead of using single variables .
List collection Type :
List is collection of similar datatypes stored in the single variable .
We can assign the values to the list dynamically. List allows duplicate values to stored.
Example :
List<account> accList=new List<account>();
AccList can hold any number of accounts .
/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/
List<account> accList=new List<account>();
for(Integer i=0;i<5;i++) {
Account a = new Account(Name='TestAccount' + i);
accList.add(a);
}
System.debug('Accounts stored in the AccList is :'+accList);
Once it is executed click on Debug check box for the records stored in accList.
AccList contains five account records in its five indexes .
Index 0 --contains account1
Index 1 --contains account2
Index 2 --contains account3
Index 3 --contains account4
Index 5 --contains account5
List Methods :
For example List.add() method adds the elements to the existing List .
We also have many other methods in the list class as mentioned below .
- 1.AccList.size()--Returns Size of the List.
- 2.AccList.clear()--Delete all the records stored in the list .
- 3.AccList.clone()--Create duplicate copy of existing list .
- 4.List.contains('test')--Search for the element mentioned between brackets and returns trueif it matches with the existing list .
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_list.htm#apex_methods_system_list
Set collection Type :
Example :
Set<String> strList=new Set<String>();
strList.add('Maisel');
strList.add('Tom');
strList.add('Reade');
strList.add('Reade');// Trying to add duplicate variable .But Set does not store it for second time.
System.debug('Accounts stored in the strList is :'+strList);
Once it is executed click on Debug check box for the records stored in accList.
You can see strList contains only three values(Maisel,Tom and Reade).
Map collection Type :
Funny and Easy Example :Assume all the rooms in an apartment is values in the map and each key to unlock the room is Key in the map . Each room has unique Key to unlock the room and no two keys will be same in an entire apartment . Believe us this examples make the map simpler to understand .
Don't get angry if your apartment have same keys to open two rooms ☺☺☺(Ignore My Strange Jokes).
Example 1 :
Map<Integer,String> myMap= new Map<Integer,String>();
//Inserting the values into the map
myMap.put(1,'FirstElement');
myMap.put(2,'SecondElement');
myMap.put(3,'ThirdElement');
myMap.put(4,'FourthElement');
myMap.put(5,'FifthElement');
//Now myMap contains five values associated with the five keys(Unique)
Example 2 :
/*Go to Developer Console>>Debug>>Open Execute Anonymous Window and execute the following code*/
List<account> accList=new List<account>();
accList=[select id,Name from account Limit 20];//Querying the existing records into the list
Map<Id,Account> accMap= new Map<Id,Account>();
for(Account acc:accList) {
accMap.put(acc.id,acc); // Adding the accountID as key and Account record as value to the accMap
}
System.debug('Accounts stored in the accMap as Key-value pair :'+accMap);
Once it is executed click on Debug . You can see Id of the record on left side(Key) and Account record on right side(Value) .
Map Methods :
Example1 :
Map.put(Key,Value)--Used to store the new values into the map dynamically as shown in above example.
Example2 :
Map.get(Key)--Map returns the value matching the key passed .
Again from our funny example ,Once you entered into the apartment you will be given with key to open the room
Likewise if you pass the id of the account ,Map will be returned with the account record .
accMap.get('0010I00002Juvstyu');//Returns the account record with id '0010I00002Juvstyu'
Usage Of Salesforce Collections in Apex Trigger :
//The below Trigger helps to ignore duplicate emails in the Author object .
trigger DemoTrigger2 on Author__c (before insert,before update) {
List<Author__c> accList=new List<Author__c>([select Author_Email__c from Author__c]);
map<String,Author__c> accmap=new map<String,Author__c>();
for(Author__c acc:accList){
accmap.put(acc.Author_Email__c,acc);
}
if(Trigger.isinsert&&Trigger.isbefore){
for(Author__c acc:Trigger.new){
if(accmap.get(acc.Author_Email__c)!=null){
acc.adderror('Email already exists');
}
}
}
}
Likewise if you pass the id of the account ,Map will be returned with the account record .
accMap.get('0010I00002Juvstyu');//Returns the account record with id '0010I00002Juvstyu'
Usage Of Salesforce Collections in Apex Trigger :
//The below Trigger helps to ignore duplicate emails in the Author object .
trigger DemoTrigger2 on Author__c (before insert,before update) {
List<Author__c> accList=new List<Author__c>([select Author_Email__c from Author__c]);
map<String,Author__c> accmap=new map<String,Author__c>();
for(Author__c acc:accList){
accmap.put(acc.Author_Email__c,acc);
}
if(Trigger.isinsert&&Trigger.isbefore){
for(Author__c acc:Trigger.new){
if(accmap.get(acc.Author_Email__c)!=null){
acc.adderror('Email already exists');
}
}
}
}
Great Information.
ReplyDeleteThank you.
Thankyou for the blog.
ReplyDeleteHi there. I couldn't get the last trigger to test correctly after creating an Author objectr with firld Author Email. I successfully entered the same email for to different Author records. (If that was your meaning of duplicate emails?)
ReplyDeleteMakes sense and easy to understand
ReplyDeleteThank you for the blog. It is easy to understand.
ReplyDeletethankuu so much for this blog.. its very helpful.. thanku
ReplyDeleteFantastic breakdown in Salesforce! The article succinctly covers key terminology, characteristics, and practical tips. Super helpful for anyone navigating Salesforce development. Kudos to the author for such valuable insights.
ReplyDeleteGreat insights on Salesforce ! Clear and helpful breakdown. Excited to apply these tips in my projects. Thanks for sharing
Salesforce Time Tracking Integration