List in Apex Collections

List in Apex Collections

List
– Collection of ordered elements which will accept duplicate elements.
– Element is located using index.
– Size is dynamically increased or decreased during run time.

Syntax:

List<dataType> listName = new List<dataType>();

dataType – Primitive, Object or Userdefined.

The keyword “new” allocates memory to the reference variable ‘listName’.

Example:

List<Integer> ages = new List<Integer>();
List<Account> accs = new List<Account>();

List can be processed using instance methods belong to list class.

List Methods and its purpose

Instance Methods Purpose
add(listElement) To add an element
add(index, listElement) Inserts an element into the list at the specified index position.
addAll(fromList / fromSet) Adds all of the elements in the specified list/set to the list that calls the method. Both lists must be of the same type.
clear() Initialize the list. Makes the list size to zero
clone() Makes a duplicate copy of a list
equals(list2) Compares the lists and returns true if lists are same. This expects the order to be in same order between the lists.
get(index) Returns the list element for a specified index.
isEmpty() To check if list is empty or not.

Returns true if list is empty

remove(index) Removes list element at a specified index
set(index, listElement) Replace a list element at a specified index.
size() Returns the number of elements in a list.

The cleared list will return zero.

sort() Sorts the items in a list

add() – To add an element

Example: List of Names

List<String>  listNames = new List<String>();
listNames.add(‘Ranjith’);
listNames.add(‘Satish’);
listNames.add(‘David’);
listNames.add(‘Swetha);
listNames.add(‘David’);
listNames.add(‘Ranjith’);
listNames.add(‘Vinesh’);
//Display the above list in developer console’s log
System.debug(listNames);

Output:
(Ranjith, Satish, David, Swetha, David, Ranjith, Vinesh)

This denote the list maintains the order of insertions and accepts duplicates

Sort() – Sorts the items in a list
listNames.sort();
System.debug(listNames);

Output:

(David, David, Ranjith, Ranjith, Satish, Swetha, Vinesh)

remove() – remove list element in a specified index
To remove the 2nd element in the above list – listNames

listNames.remove(1); //index always starts with zero
System.debug('After an element in index 2 is removed : ' + listNames);

Output:
After an element in index 2 is removed : (David, Ranjith, Ranjith, Satish, Swetha, Vinesh)

get(index) – Returns the list element for a specified index.

To read 3rd element in the list – listNames
System.debug(listNames.get(2));

Output:
3rd element : Ranjith

addAll() – Adds all of the elements in the specified list/set to the list that calls the method. Both lists must be of the same type.

List<String> empNames = new list<String>();

empNames.add('Ranjith');
empNames.add('Uma');
empNames.add('Mohan');
empNames.add('Uma');
empNames.add('Satish');

Add all elements from list – listNames to empNames

empNames.addAll(listNames);
System.debug('The final empNames : ' + empNames);

Output:
The final empNames : (Ranjith, Uma, Mohan, Uma, Satish, David, Ranjith, Ranjith, Satish, Swetha, …)

Declare list of sObjects

List<account> accList = new List<account>();

account a1 = new account();
a1.name = 'CTS';
a1.phone = '123';
a1.industry = 'energy';
a1.annualRevenue = 500000;

accList.add(a1);  //add element (account record) into a list of similar type

account a2 = new account();
a2.name = 'TCS';
a2.phone = '335';
a2.industry = 'Apparel';
a2.annualRevenue = 450000;

accList.add(a2);

account a3 = new account();
a3.name = 'Reynolds';
a3.phone = '434';
a3.industry = 'Apparel';
a3.annualRevenue = 320000;

accList.add(a3);

system.debug('list of account records ' + accList);

Output:

|list of account records (Account:{Name=CTS, Phone=123, Industry=energy, AnnualRevenue=500000}, Account:{Name=TCS, Phone=335, Industry=Apparel, AnnualRevenue=450000}, Account:{Name=Reynolds, Phone=434, Industry=Apparel, AnnualRevenue=320000})

Adding contacts for related accounts

List<Contact> conList = new List<Contact> ();

Contact c1 = new Contact();
c1.lastName = ‘Krishnan’;
c1.firstName=’Ranjith’;
c1.accountID=a1.id; //to add contact for the above account a1

Note: The list is a temporary entity that exists for a transaction. Hence the adding a contact as shown above should be executed in the same transaction.

Use Cases:

  1. Get list of accounts names from the above list – accList and keep it in a primitive list.
  2. Get total annual revenue of all the accounts whose industry is ‘Apparel’
  3. Copy the employee names from the list empNames to contact conList

Additional Examples:

List of RollNos
list<integer> rollnos  = new list<integer>();
rollNos.add(100);
rollNos.add(50);
rollNos.add(125);
rollNos.add(200);
rollNos.add(5);
rollNos.add(50);
system.debug('actual list: ' + rollNos);
system.debug('------------------------');

//add(index, element)
rollNos.add(2, 99);
system.debug('after inserted element 99 :' + rollNos);
system.debug('------------------------');

//sort()
rollNos.sort();
system.debug('after sorted the list :' + rollNos);
system.debug('------------------------');

//size() - no of elements in the list
system.debug('size of elements in rollNos :' +rollNos.size());
system.debug('------------------------');

//isEmpty() – true if list is not having any element
system.debug(‘is empty? :’ + rollNos.isEmpty());

Hence, List in Apex Collections can be defined as a collection of ordered elements since it is accessed by index and maintains the order of insertion. Also it would accepts duplicates. We have other types of collections as well. They are Set and Map.

Leave a Comment