Interview Questions on Collections: List, Set and Map




Q What is Collection in Salesforce?

The collection is the type variables which can store multiple numbers of records. It can increase and decrease dynamically.

Q Difference between 1 dimensional and 2 dimensional list?

One-Dimensional Lists: When items in the list are linear and we could access them with one index only.

List<Integer> listint = new List<Integer>{0, 1, 2, 3}

A two-dimensional: list is list of lists 
List<List<Integer>> listOfListInt = new List<Integer> { {0, 1, 2, 3}, {3, 2, 1, 0}, {3, 5, 6, 1}, {3, 8, 3, 4} };     
Q Can we predefine length of the list?
We can use array notation to create a list of pre-allocated length

Q When we should use Map over the list?

Apex code has limitation of  Number of code statements that can be executed. While writing Apex code, we should take care of number of code statement that are  executed to avoid governor limits.



A main use for maps is to reduce the number of executed code statements and to make our code more efficient.

Scenario1
We should try to use Map when working with an update trigger. Especially when we need to check if some field has changed value. Using maps we can loop through all old and new values in one loop

Scenario2
Using trigger populate the Account Type on the Contact record (only insert scenario).

Option 1 use List:is having a List of Accounts, where in we have to loop through the matching Account every time to populate the Acc_Type in the second for loop.

Option 2 use Map: is having a Map of Accounts with Id and Account as the Datatypes. Hence we can directly get the corresponding Account record and populate the Acc_Type easily.


Q. how to check whether a list is null or empty?

 isEmpty()  checks both null and empty string.

Q.What is the different between list.Size() > 0 vs list != null vs list.IsEmpty()?

The List.Size() > 0 will check whether the list has any record in it or not.
The List!=null will be use full when we have not initialize the list. It is not helpfull to check the whether the list has any record or not. This is a waste of CPU time, because:
(a) records will never be null
(b) iterating over an empty list is acceptable
List.isEmpty() then it also check whether the list has any record or not.

Q.Will the set maintain insertion Order?


 No, the elements in the Set are not reserving insertion order.

Q.Will the list maintain insertion Order?

 Yes, the elements in the List are reserving insertion order.

Q.Can we sort the values in the set? 


A:No, we can’t, because internally arrange the values in ascending order.


Reference

http://www.sfdcpoint.com/salesforce/gets-maps-soql-queries-salesforce/
https://salesforce.stackexchange.com/questions/133883/when-should-i-use-maps-and-when-should-i-use-lists-in-apex
http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html
https://sivatejaforce.wordpress.com/2011/02/03/hello-world/



Share this

Related Posts

First