function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rain.Rain. 

When to use lists/maps/sets?

Hello

Can someone explain when to use different collection types in Apex with some real-life scenarios? 

Some explanation why a certain collection is used would be awesome. (Especially on maps!)

Additionally, are there any collection-specific limitations or best practises which would be good to know?

Thank you!
ManojjenaManojjena
Hi Rain,

Please check this link .If you have any doubt please let us know .
Also one scenario is there you can check ,
http://manojjena20.blogspot.in/2013/05/master-in-apex-collection.html  

Let me know if it helps !!
Thanks 
Manoj
Amit Chaudhary 8Amit Chaudhary 8
Hi Rain,

List,Set,Map are called collections in Apex:

List: A list is an ordered collection
so use list when you want to identify list element based on Index Number.(Lsit can contain Duplicates)
EX: List<Account> accList = new List<Account>();
List<Integer> myList = new List<Integer>(); // Define a new list
myList.add(47);                    // Adds a second element of value 47 to the end 
                                       // of the list
Integer i = myList.get(0);                   // Retrieves the element at index 0
myList.set(0, 1);                           // Adds the integer 1 to the list at index 0
myList.clear();                    // Removes all elements from the list


Set: A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements.
So, use set if you want to make sure that your collection should not contain Duplicates.
EX: Set<Account> accSet = new Set<Account>()


Map: A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type or an Apex object.
EX: Map<Id, Account> accMap = new Map<Id, Account>();
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry');                  // Insert a new key-value pair in the map
m.put(2, 'Second entry');                  // Insert a new key-value pair in the map
System.assert(m.containsKey(1));  // Assert that the map contains a key
String value = m.get(2);               // Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet();       // Return a set that contains all of the keys in the maListsp



User-added image


To Answer your question.
if we need list of account that what we can get like below :-
List<Account> lstAccount = [select id,name from Account limit 10];
But if base on ID we need to get account detail in that we can use the map
Set<Id> setAccId = new Set<ID>();
List<Contact> lstCont = [select accountID,FirstName,lastName from contact limit 10];

For(Contact cont: lstCont)
{
	setAccId.add(cont.accountID); // Get All AccountId
}

// GEt All Account with key value pare
Map<Id,Account> mapAcc = new Map<Id,Account>( [ select id,name from Account where id in :setAccId ] ); 

For(Contact cont: lstCont)
{
	if( mapAcc.containsKey(cont.accountID) ) 
	{
		Account acc = mapAcc.get(cont.accountID);
		System.debug('Account------------>'+acc);
		// here due to map we dnt need to execute query inside the for loop to get Account Record
	}
}

There is a realtime situation where-in we need to loop through the collection of records and get the appropriate value from the matching record.

Requirement is:
      Using trigger populate the Account Type on the Contact record (only insert scenario).

To achieve this requirement, here I am mentioning using trigger, so planning to write a trigger:

If we use List and not Map
trigger ContactTriggerWithList on Contact (before insert) {
    // Here taking the Set because we don't need to maintain duplicate
    Set<Id> accIdSet = new Set<Id>();
    
    for(Contact con: Trigger.new) {
        if(con.AccountId != null) {
            accIdSet.add(con.AccountId);
        }
    }
    
    if(!accIdSet.isEmpty()) {
        List<Account> accList = [Select Id, Name, Type from Account where Id IN: accIdSet];
        
        for(Contact con: Trigger.new) {
            if(con.AccountId != null) {
                for(Account acc: accList) {
                    if(con.AccountId == acc.Id) {
                        con.Acc_Type__c = acc.Type;
                    }
                }
            }
        }
    }
}
Same Trigger using the Map:
trigger ContactTriggerWithMap on Contact (before insert) {
    // Here taking the Set because we don't need to maintain duplicate
    Set<Id> accIdSet = new Set<Id>();
    
    for(Contact con: Trigger.new) {
        if(con.AccountId != null) {
            accIdSet.add(con.AccountId);
        }
    }
    
    if(!accIdSet.isEmpty()) {
        Map<Id, Account> accMap = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN: accIdSet]);
        
        for(Contact con: Trigger.new) {
            if(con.AccountId != null) {
                con.Acc_Type__c = accMap.get(con.AccountId).Type;
            }
        }
    }
}
If you compare both the triggers,

Trigger 1 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.

Trigger 2 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.

Hope this will clear you actual doubt.

Please do let me know if it helps you.


Thanks
Amit Chaudhary
 
raj_sfdccraj_sfdcc
Hi Rain,

List-You can use list when you are dealing with bulk records.

Set-You can use set when you require to deal with Unique records (Set is similar to List collection type ,The only difference is Set does not allow duplicate values ).

Map-Map can help you when you are dealing with parent-child executions .

Please find the below post for basic to advacned examples.
How to use collections in salesforce (https://salessforcehacks.blogspot.com/2020/01/collections-in-salesforce-list-set-map.html)