Salesforce Collections
Collections are the data structures in Apex (Salesforce programming language) that allow you to work with data as an array, list and set. Collections are an integral part in bulk operations providing efficiency, a live connection and increase the performance by hitting db only once. Collections are the group of similar types. There are three types of Salesforce collections. They are
- List
- Set
- Map
List
List is an ordered collection of elements which will allow duplicates. A list is an ordered collection of typed primitives SObjects, user-defined objects, Apex objects or collections that are distinguished by their includes.
- The index position of the first element in a lsit is always ‘0’.
- To declare a list, use the list. keyword followed by the primitive data, SObject, nested list, map, or set type within <>characters.
Syntax
List<datatype> listName = new List<datatype>();
where datatype
allows both primitive datatypes and non-primitive datatypes.
The size of a list changes dynamically when items are added to the list or removed from the list.
List<String> accountNames = new List<String>();
accountNames.add('Account1');
accountNames.add('Account2');
Methods: Common methods include add()
, get()
, size()
, and remove()
.
List Methods
Add
list.add() method adds the values (items) to the list.
List<String> colors =new List<String>(); colors.add('Red'); colors.add('White'); colors.add('Black');
or, you can add the items in a single statement as shown below:
List<String> colors =new List<String>{'Red','White','Black'}
Get
list.get(index) retrieves value from list present at index position.
String getcolor = colors.get(1); // we get the value is 'White' in to getcolor veriable.
Set
list.set(index, value) replaces a former value with the specified value at the given index.
colors.set(1,'Green'); // List has value at index ' 1 ' is White is changed to Green.
Size
list.size() return the number of elements in the list.
colors.size(); // Gives the size of colors list is '2'
Clear
Remove the elements from the list.
colors.clear();
Example Inserting 100 contacts in contacts object
public class ContactInsertion { List<contact> contactList = new List<contact>(); public void methodName() { for(integer i=0; i<100 ; i++ ) { contact cont = new contact(lastname = 'contact' + i); contactList .add(cont); } insert contactList ; } }
Go through this reference for the more list methods.
Set
Set is an unordered collection of elements which will not allow duplicates. A set is an unordered collection of primitives or SObjects that do not contain any duplicate elements.To declare a set, use the set keyword followed by the primitive data type name within < > characters
Syntax
Set<datatype> setName = new Set<datatype>();
- data type allows only primitive datatypes and SObjects.
- We cannot get the retrieve the data based on index because set does not have index.
Go through this reference, for the all variations of set methods.
Example:-
set <string> s= new set < string > ();
To access elements in a set use the system methods provided by Apex.
<Integer> s=new set <Integer>(); => Define a new set
S.add (1); => Adding an element to the set
Boolean b= s.contains(1); => It will returns true when the element‘1’ contains within the set.
s.remove (1); => Remove the element from the set.
Map
Map stores key-value pairs. A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive datatype while values can be primitive, sobject, collection type or Apex object.
- To declare a map, use the Map keyword followed by the data types of the value within < > characters
Syntax
Map<datatype_key,datatype_value> mapName = new Map<datatype_key,datatype_value>();
datatype_key
is the storage datatype of key and it allows only primitive datatypes and should be unique.datatype_value
is the datatype of value. Both primitive & non-primitive datatypes are allowed. Duplicates are allowed for values.
Example:-
Map < string, string> m=new map <string, string> ();
Note:- Similar to lists, map values can contain any collection and can be nested within one another. A map can only contain up to five levels of nested collections inside it.
Map Methods
put()
Insert a key-value pair or replaces a value with the given value for the key.
map.put(key,value);
get()
Retrieves the value for a key.
map.get(key);
keySet()
Retrieves all the keys and return type is set;
map.keySet();
values()
Retrieves all the values and return type is list;
map.values();
size()
Return the number of components in the map.
map.size();
Example to Create a map of Account Ids and Account objects
public class AccountMapPopulation{ // Creating map with account id and account object map <Id,Account> accountIdMap =new map<Id,Account>(); public void methodName(){ // creating the accounts account acc1 = new account (name ='account1' , industry = ' Banking'); account acc2 =new account(name =' account2' , industry = 'Agriculture'); account acc3 = new account(name='account3' , industry='Banking'); // populating the map with account id and account object accountIdMap .put(acc1.id,acc1); accountIdMap .put(acc2.id,acc2); accountIdMap .put(acc3.id,acc3); } }
Go through this reference for the more map methods.