Collections in apex salesforce - List

Apex gives us three types of collections.
1. List
2. Set
3. Map

List and Set are almost similar with few differences that we will discuss in another article. Map is different from list and set but incorporates both in it. It consists of key and values. In this article lets discuss List and various points on List and how to use it while building our logic in apex.

1. Lists

A list is nothing but a collection of elements which are marked by indexes, it is similar to array that we have learned in other languages. 
List can store any of the below data types-
Primitive types like integers, strings or sObjects even user defined types like wrapper classes and also built in apex types. 

List are ordered collection of elements unlike set which is unordered.
Below are some points that needs to be considered while using lists-
1. The List collection indices begin at 0


2. Lists can be nested with one another and this can go upto total 5 levels.


3. To declare a list keyword 'List' is used for example as below,
    List<String> intlist = new List<String>();

 
4. there are various methods that salesforce provides to manipulate data in a list collection. As an example add() this is one of the methods that is extensively used. This method allows us to add new elements in the list. As an example below statement adds new integer to the list defined in point 3.
   intlist.add(4);
   intlist.add(7);

 
5. A SOQL query results needs to be collected in List. A SOQL query returns collection of sobject that needs to be stored in a list of that type, that is return type of soql is list unless limit 1 is used in which case sobject type can be sued. As an example below
 List<account> accList = [Select id,name from account where createddate = system.today()];

 
6. Lets see few other methods that can be used to manipulate data in list collection.
    You can use Clear() method to clear all the data present in list. for example intlist.clear();
   You can set data at any specific index by using set method. for example below set element at second position as 2
    intlist.set(1,2);   


7. List can store duplicate elements in it which is not allowed in case of Sets


8. We can iterate over all the elements in list using advanced for loop wherein we need not check for last index or increase the counter. We can simply iterate over it and everything is taken care of as below.
   for(integer in : intlist){
        system.debug('integer values is'+in);
   }


Next>> Apex Collection - Set 

No comments:

Post a Comment