Collection In Apex

The Collection in Apex is a framework that provides a way to store and manipulate the group of similar types objects.It is completely dynamic in nature which means it will grow based on the size of incoming data/elements.

Real time example of Collection: Let’s suppose you need to design inbox like gmail the size of gmail’s inbox grows according to the size of incoming emails where we are not sure how many emails are in the way to come in inbox so we need to design inbox in a way so that it will hold dynamic data and can grow accordingly based on incoming size of data/elements.

There are basically, 3 types of collection – List, Set and Map.

List: It is an ordered collection of primitives, sObjects, collections, or Apex objects based on indices as well as List allows duplicacy of the elements.

Set: An unordered collection of unique primitives, sObjects, collections, or Apex objects as well as Set won’t allows duplicacy of the elements.

Map: A collection of primitive unique keys that map to single values which can be primitives, sObjects, collections, or Apex objects.

Note : – Collections do not support adding or removing elements/values while iterating over the collections.

List Example as below:

List l = new List();

Methods of List :

  1. Add: Add the values to the list.
  2. Example :

    apexprogram

  3. Get: Retrieve values from list using index.
  4. Example :

    apexprogram1

  5. Set: Replaces a former value with the value at given index.
  6. Example :

     colors.set(1,’Blue’); — List has value at index ‘ 1 ‘ is White is changed to Blue.
    
  7. Size: Return the number of elements in the list.

    Example :

    colors.size(); —- Gives the size of colors list is ‘2’
    
  8. Clear: Remove the elements from the list.
  9. Example :

     
    colors.clear();
    
  10. Contains : This Method Returns true if the list contains the specified element.
  11. Example :

     
    List stringList = new List{'a', 'b'};
    Boolean result = stringList.contains('z');
    System.assertEquals(false, result);
    
    
  12. Equals : This method Compare the list with the specified list and returns true if both lists are equal. Two lists are only equal if their elements are equal and are in the same order.
  13. Example :

     
    List stringList = new List{'a', 'b'};
    List stringList2 = new List{'c', 'd'};
    Boolean result;
    result= stringList.equals(stringList2);  // false
    
  14. Isempty : This method Returns true if the list has no elements.
  15. Example :

     
    List stringList = new List{'a', 'b'};
    Boolean result = stringList. Isempty()
    System.assertEquals(false, result);
    
    
  16. Sort: This method Sorts the items in the list in ascending order.
  17. Example :

     
    List listTest = new List();
           	listTest.add('D');
           	listTest.add('K');
           	listTest.add('A');
           	System.debug(listTest);   // (D,K,A)
           	listTest.sort(); //sort in ascending order
           	System.debug(listTest); // (A,D,K)
    

Example: Inserting 100 contacts in contacts object

public class ContactInsertion{
    list contactList = new list();
    public void methodName(){
     for(integer i=0; i<100 ; i++ ){
      contact cont = new contact(lastname = ‘contact’ + i);
      contactList .add(cont);
     }
     insert contactList ;
    }
}

Set Syntax as below:

Set s = new Set();

Note : Same methods which we used in List. Except some Additional methods which are as follows:-

  1. containsAll(listToCompare): This method Returns true if the set in context contains all the elements in the list to be compared.
  2. retainAll(listOfElementsToRetain): This method Retains only the elements in the set which are contained in the specified list.e.g
         Set mySet = new Set{1, 4, 3};
         List myList = new List{1, 3};
         Boolean result = mySet.retainAll(myList);
         System.assertEquals(true, result); 
	

Map syntax as below:

Map myFlavors = new Map();
    myFlavor(‘Honey’, ‘Sweet’);
    myFlavor(‘Anchovies’, ‘Salty’);
    myFlavor(‘Vinegar’, ‘Tart’);

Methods of MAP :

  1. Put():- Insert a key-value pair or replaces a value with the given value for the key.
    map.put(key,value);
  2. Get():- Retrieves the value for a key.
  3. keySet():- Retrieves all the keys and return type is set
    map.keySet();
  4. values():- Retrieves all the values and return type is list
    map.values();
  5. Size():- Return the number of components in the map.
    map.size();

apexprogram2

List vs Set vs Map
List Set Map
It is a collection of elements. It is a collection of elements. It stores data in a key value format. With each key pointing to a data value.
It is ordered in nature, that is, each element is stored sequentially and has an index. It is unordered in nature. It is unordered in nature.
It can contain primitive or non-primitive data types. It can contain primitive or non-primitive data types. It can contain primitive or non-primitive data types.
It can have duplicate values. It cannot have duplicate values. It cannot have duplicate keys but the value for two unique keys can be the same.

Syntax :
list<String> textList = new list<String>();

Syntax :
set<String> textSet = new set<String>();

Syntax :
map<String,String> textMap = new map<String,String>();

Subscribe Now