List in Salesforce

Hello friends, Welcome to sfdcAmplified. Today we will learn about list in Salesforce.

Preface

I will encourage you to read the previous blog post where I have written Datatypes and variables in Apex to understand this blog post more clearly.

Topics to be covered

  • What is a collection?
  • What is a list?
  • Different methods of a list

What is a Collection?

Collections is a type of variable that can store multiple number of records.

There are three types of collection

  1. List Collection
  2. Set Collection
  3. Map Collection

What is a List?

  • A list is an ordered collection of elements. 
  • List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types
  • List allows duplicate value

Lets firstly see the syntax of List

Syntax:

List<datatype> variablename = new List<datatype>();

Lets understand it with help of a Example:

Explanation

In the above image you can see that there is a list named ‘colors’. Values are stored in the below position:

index position 0 = ‘red’
index position 1 = ‘blue’
index position 2 = ‘green’

Syntax

List<String> colors = new List<String>{'red','blue','green'};
system.debug(colors);

Output

Example 2

List<String> bollywoodActresses= new List<String>{'Deepika','Anushka','Alia'};
System.debug('index 0---' + bollywoodActresses[0]);
System.debug('index 1---' + bollywoodActresses[1]);
System.debug('index 2---' + bollywoodActresses[2]);

Explanation

Here values are stored as,
index postion 0 = Deepika
index postion 1 = Anushka
index position 2 = Alia
In another way, we can assign values dynamically when we are creating a list.

Output

Methods in list

There are few methods available in list
add(list Element)
add(index, list Element)
addAll(from List)
addAll(from Set)
clear()
clone()
remove()
size()
equals(list2)
get()
sort()
hashCode()
isEmpty()

add(ListElement)

Adds an element to the end of the list.
List<Integer> myList = new List<Integer>{32,56};
myList.add(47);
system.debug(myList);
Explanation
I have created List with variablename ‘myList’. It holds integer data type.
Index 0 = 32
index 1 = 56
Now I am using add method to add 47 to the list.
It will come on the 2nd index of the list.
i.e. Index 2 = 47

addAll(fromList)

Adds all of the elements in the specified list to the list that calls the method. Both lists must be of the same type. 
List<string> bollywoodActress = new List<string>(); 
bollywoodActress.add('Deepika'); 
bollywoodActress.add('Kareena'); 
bollywoodActress.add('Alia'); 
System.debug(bollywoodActress); 

List<string> bollywoodActor = new List<string>(); 
bollywoodActor.add('Salman'); 
bollywoodActor.add('Ranveer'); 
bollywoodActor.add('Ranbir'); 
System.debug(bollywoodActor); 

bollywoodActor.addAll(bollywoodActress); 
system.debug('Both list names are '+' '+bollywoodActor+'');

Explanation
1. I have created a list  named ‘bollywoodActress’ which contains bollywood actresses
2. I have created another list ‘bollywoodActor’ which contains bollywood actor
3. Now I add all the elements of ‘bollywoodActress’ into ‘bollywoodActor’
Result is both the names are in one list – (Salman, Ranveer, Ranbir, Deepika, Kareena, Alia)
Output
addAll(fromSet)
It is used to add all the elements in the set when this method is called, and both set and list elements should be of same type.
 List<string> bollywoodActress = new List<string> {'Deepika', 'Kareena','Alia'};
Set<string> bollywoodActor = new Set<string> {'Salman', 'Ranveer', 'Ranbir'};
        bollywoodActress.addAll(bollywoodActor);
        system.debug(bollywoodActress);
Output
Result
(Deepika, Kareena, Alia, Salman, Ranveer, Ranbir)

size()

It is used to get the total number of elements in the list.
Example: bollywoodActor.size();
List<string> bollywoodActor = new List<string>(); 
bollywoodActor.add('Salman');
bollywoodActor.add('Ranveer');
bollywoodActor.add('Ranbir'); 
System.debug(bollywoodActor);
System.debug(bollywoodActor.size());

Output

remove()

It removes the list element stored at specific index, returning the element that was removed.
   List<string> bollywoodActress = new List<string>();
       bollywoodActress.add('Deepika');
       bollywoodActress.add('Kareena');
       bollywoodActress.add('Alia');
      System.debug(bollywoodActress);
       bollywoodActress.remove(2); //remove 2nd position value.
      System.debug(bollywoodActress);
Explanation
Initial list – (Deepika, Kareena, Alia)
Index 0 – Deepika
index 1- Kareena
Index 2 – Alia
Used removed method to remove the element from index 2
output – (Deepika, Kareena)
Output
sort()
This method sorts list in ascending order. 
List<string> bollywoodActress = new List<string>();
       bollywoodActress.add('Deepika');
       bollywoodActress.add('Kareena');
       bollywoodActress.add('Alia');
       System.debug(bollywoodActress);
       bollywoodActress.sort(); //sort in ascending order
       System.debug(bollywoodActress);
Output

clear()

It will remove all the elements from the list. Hence the length of that list will be zero. 
  List<string> bollywoodActress = new List<string>();
       bollywoodActress.add('Deepika');
       bollywoodActress.add('Kareena');
       bollywoodActress.add('Alia');
       System.debug(bollywoodActress);
       bollywoodActresses.clear();
       System.debug(bollywoodActress);
Output

get(index) 

It returns the element which is at given index. 
bollywoodActresses.get(1)
List<string> bollywoodActress = new List<string>(); 
bollywoodActress.add('Deepika'); 
bollywoodActress.add('Kareena'); 
bollywoodActress.add('Alia'); 
System.debug(bollywoodActress.get(1));
Output
clone() 
It creates another copy of the list.
 List<string> firstList = new List<string>();
       firstList.add('Deepika');
       firstList.add('Kareena');
       firstList.add('Alia');
       System.debug('firstList---' + firstList);
  
List<string> secondList = new List<string>();
      secondList=firstList.clone();
      System.debug('secondList----'+ secondList);
Explanation
First List – Deepika, Kareena, Alia
SecondList is null initially then clone method is used to clone the elements of first list into second
SecondList-  Deepika, Kareena, Alia

equals(List)

Compares the list with the specific list and returns true if both are equals, otherwise, returns false.
 List<string> bollywoodActress = new List<string>();
       bollywoodActress.add('Deepika');
       bollywoodActress.add('Kareena');
       bollywoodActress.add('Alia');
       System.debug(bollywoodActress);
      
       List<string> bollywoodActor = new List<string>();
       bollywoodActor.add('Salman');
       bollywoodActor.add('Ranveer');
       bollywoodActor.add('Ranbir');
       System.debug(bollywoodActor);
       Boolean result;
       result=bollywoodActor.equals(bollywoodActress);
       system.debug(result);
Explanation
There are two list ‘bollywoodActress’ and ‘bollywoodActor’. We compare that the two lists have same values or not. If the two list have same values then result should come as true otherwise false.
Here both list do not have same values so the result is false
Output

hashCode()

Returns the hash code corresponding to this list and its contents. 
Lets understand this concept in little more depth to get a strong grasp of it. It is interesting concept.
Explanation

Hashing is a fundamental concept of computer science.  By definition, a hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.

Why we use hashcode?

Hashcode is used to increase the speed up searching. Lets understand with help of an example. Suppose we need to search a List for a given value.

Case 1 List not sorted: If list is not sorted then search needs examining each elements of the list.

Case 2 List sorted:  If the list is sorted, we can use the binary search, and therefore reduce the worse-case run-time complexity to O(log n). ( What is this? Read Big O Notation to get more clarity)

We could search even faster if we know in advance the index at which that value is located in the list.

Image result for magic cartoon

There is a magic function that tell us the index for a given value. With this magic function our search is reduced to just one probe, giving us a constant runtime O(1). Such a function is called a hash function . A hash function is a function which when given a key, generates an address in the table.

This method will return an integer as a result by mapping an integer to internal memory address in which object is stored.

It always returns a number for an object.Thus, we say that our hash function has the following properties

  • two equal objects will always have the same number
  • two unequal objects not always have different numbers

Now that you have got the clear understanding of hashcode, we can go ahead and see the example usecase of hascode

List<string> bollywoodActor = new List<string>();
bollywoodActor.add('Salman'); 
bollywoodActor.add('Ranveer');
bollywoodActor.add('Ranbir'); 
System.debug(bollywoodActor); 
System.debug(bollywoodActor.hashCode()); //Output: 485459500
isEmpty()
True if the list has zero elements.
List<string> bollywoodActor = new List<string>();      
 bollywoodActor.add('Salman');    
 bollywoodActor.add('Ranveer');     
 bollywoodActor.add('Ranbir');     
System.debug(bollywoodActor); 
 System.debug(bollywoodActor.isEmpty());
//Output: false
Output
Exercise

Create a list of your favorite fruits and then add the fruits in the second list. Later remove the first list. So list of your favourite fruits will be in the second list. Let me know in the comment section if you face any issue.

Conclusion

List and all its method are highly important. Please practice all the methods to get complete grasp of this concept.

I hope you enjoy the article. For more of these articles stay tuned!

Get latest updates

If you like the Video then subscribe to Youtube Channel

If you like the Article then subscribe to the Blog

Together we can learn faster

You can join the Whatsapp group 

You can join Facebook group

You can join Twitter

You can join Instagram 

Reference

Collections in Salesforce

Collections

Concept of hashing

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes