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
Vijay@sfdcVijay@sfdc 

any one share same example using LIST and MAP

Hello All,
   i have gone through list and map, would any one share same example using LIST and MAP using 2 object. i am still confused when do i use list and when do i use map? please give me one common example , how MAP reduces code over LIST ?

Thanks,
 
Mahesh DMahesh D
Collections, List, Set, Map
 
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>();

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>();

Please look into below example which will give you an idea about List, Set and Map.

 
Example:
 
public class CollectionExample {
    public void printList() {
        List<Integer> li = new List<Integer>();
       
        li.add(1);
        li.add(5);
        li.add(3);
        li.add(1);
        li.add(2);
        li.add(4);
        li.add(6);
        li.add(4);
        li.add(8);
        li.add(7);
       
        System.debug('========================List li:'+li);
        // ========================List li:(1, 5, 3, 1, 2, 4, 6, 4, 8, 7)
       
        for(Integer val: li) {
            System.debug('---------------------Value: '+val);
        }
    }
   
    public void printSet() {
        Set<Integer> se = new Set<Integer>();
       
        se.add(1);
        se.add(5);
        se.add(3);
        se.add(1);
        se.add(2);
        se.add(4);
        se.add(6);
        se.add(4);
        se.add(8);
        se.add(7);
       
        System.debug('========================Set se:'+se);
        // ========================List li:(1, 5, 3, 1, 2, 4, 6, 4, 8, 7)
        //========================Set se:{1, 2, 3, 4, 5, 6, 7, 8}
       
        for(Integer val: se) {
            System.debug('---------------------Value: '+val);
        }
    }
   
    public void printMap() {
        Map<Integer, String> ma = new Map<Integer, String>();
       
        ma.put(1, 'Anu');
        ma.put(5, 'Ash');
        ma.put(3, 'Ven');
        ma.put(1, 'Swa');
        ma.put(2, 'Sar');
        ma.put(4, 'Div');
        ma.put(6, 'Dee');
        ma.put(4, 'Sac');
        ma.put(8, 'Swa');
        ma.put(7, 'She');
       
        System.debug('========================Map ma:'+ma);
        // ========================List li:(1, 5, 3, 1, 2, 4, 6, 4, 8, 7)
        // ========================Set se:{1, 2, 3, 4, 5, 6, 7, 8}
        // ========================Map ma:{1=Swa, 2=Sar, 3=Ven, 4=Sac, 5=Ash, 6=Dee, 7=She, 8=Swa}
       
        Set<Integer> kSet = ma.keySet();
        // ==============kSet:{1, 2, 3, 4, 5, 6, 7, 8}
       
        System.debug('==============kSet:'+kSet);
       
        for(Integer key: kSet) {
            System.debug('---------------------Key: '+key);
            System.debug('---------------------Value: '+ma.get(key));
        }
       
        List<String> valList = ma.values();
       
        for(String val: valList) {
            System.debug('---------------------Value: '+val);
        }
       
    }
}

Find below link for detailed explanation regarding collections:

http://share-salesforce.blogspot.in/2013/05/sfdc-data-collections-listsetmap.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections.htm
http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_core_concepts.htm
https://developer.salesforce.com/docs/atlas.en- us.apexcode.meta/apexcode/langCon_apex_collections_lists.htm
http://www.sfdc99.com/2013/09/28/data-collections-lists-sets-and-maps/

Please check below post for map method in salesforce
1) 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps.htm
3) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_sets.htm

Please let me know if this helps you.

Regards,
Mahesh
Amit Chaudhary 8Amit Chaudhary 8
Hi ,

There are to many example are given in developer guide. I will recomend you to download the Apex developer guide .
1) http://amitsalesforce.blogspot.in/search/label/Book
2) https://resources.docs.salesforce.com/sfdc/pdf/salesforce_apex_language_reference.pdf

User-added image

Please check below post for collecttion
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections.htm

Maps
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps.htm
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.
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

Lists
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_lists.htm

A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types
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

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
	}
}

We can use the Map over list to avoide query inside for loop with above example

Please let us know if this will help you

Thanks
Amit Chaudhary
Vijay@sfdcVijay@sfdc
Hello,
  Amit and mahesh thanks for your reply, could you give us any other highend and more bit more complecte example for using list and maps for looping data from differnt objects.your work is more appreciable

Thanks





 
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for some more complex example of MAP and LIST
1) http://amitsalesforce.blogspot.in/2014/11/dynamic-field-mapping-using-custom.html

Example 1:- How to get Custom setting and put in MAP
public Map<string,string> getAllMapping()
    {
        qry ='';
        try{
             for (MyLeadToLeadMapping__c mappingTableRec : MyLeadToLeadMapping__c.getall().Values())
             {
                if (mappingTableRec.Name != null && mappingTableRec.Lead_Field_API_Name__c != Null )
                {
                    MapMappingTable.put(mappingTableRec.Name , mappingTableRec.Lead_Field_API_Name__c);
                    qry += mappingTableRec.Name + ',';
                }
             }
        }
        catch(exception ex)
        {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
            Apexpages.addMessage(msg);
        }
        return MapMappingTable;
    }
Example 2:- Descibe call with map
1) http://amitsalesforce.blogspot.in/search/label/Apex%20Describe

Example 3:-  Dynamic query
public Void GetAllField()
{
 String query ='';
 String SobjectApiName = 'Account';
 Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
 Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();

 String strFields = '';
 
 for(String fieldName : fieldMap.keyset() )
 {
  if(strFields == null || strFields == '')
  {
   strFields = fieldName;
  }else{
   strFields = strFields + ' , ' + fieldName;
  }
 }

 query = 'select ' + strFields + ' from ' + SobjectApiName + ' Limit 10 ';

 List <Account> accList = Database.query(query);
 
}

NOTE:- All Above are complex one as per your request.

I will suggest you please download the apex book and try all example.
1) https://resources.docs.salesforce.com/sfdc/pdf/salesforce_apex_language_reference.pdf

Please let us know if this will help you
Mahesh DMahesh D
Hi,

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.

Regards,
Mahesh
Amit Chaudhary 8Amit Chaudhary 8
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.
A map can only contain up to five levels of nested collections inside it.


Map Structure will be like this:
Map<Key, Value>

    Key_type represents the primitive type of a map key.
    Value_type represents the primitive or sObject type of a map value.
 
To Understand the use fo map find the below 2 examples,
Example 1:-
//Fetching all accounts 
List<account> acc = [select Id from account limit 1000] ; 
 
//Creating set of all account Ids 
List<id> accIds = new List<id>() ; 
 
//Fetching Account ids 
for(Account acc : acc) 
{ 
 accIds.add(acc) ; 
}

Now if the query will return 1000 records then for loop will execute 1000 script statements. Now to avoid this we can simply write:
//Fetching all account in map vairable 
Map<id,account> Mapvar = new Map<id,account>([Select Id,Name from Account limit 1000]); 
 
//Creating list of accounts form map
List<account> accList = Mapvar.values() ; 
 
//Creating set of ids 
Set<id> accIds = Mapvar.keySet() ;

Example 2:- How to use list in VF page
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_dynamic_vf_maps_lists.htm
public Map<String,String> directors {
    get {
        return new Map<String, String> {
            'Kieslowski' => 'Poland', 
            'del Toro' => 'Mexico', 
            'Gondry' => 'France'
        };
    }
    set;
}
Your Visualforce page can show the values like this
<apex:repeat value="{!directors}" var="dirKey">
        <apex:outputText value="{!dirKey}" /> -- 
        <apex:outputText value="{!directors[dirKey]}" /><br/>
</apex:repeat>

Example 3:- Use Maps to navigate across Lists!
http://www.sfdc99.com/2014/01/25/use-maps-navigate-across-lists/

Example 4:-
http://blog.jeffdouglas.com/2011/01/06/fun-with-salesforce-collections/

Thanks
Amit Chaudhary
 
Mahesh DMahesh D
Hi SFDC Beggner,

I think he is not looking for any internet examples, he is looking more of a Realtime scenario.
Please check the realtime scenario which I gave earlier by writing the same requirement using both List and Map.

Please let us know if you need more to understand these concepts.

Please do let me know if it helps you.


Regards,
Mahesh

 
farukh sk hdfarukh sk hd
Hi,

These posts will cover about list,set,map usage and methods available and how to use map in lightning components,

https://www.sfdc-lightning.com/2018/09/collection-in-salesforce.html

https://www.sfdc-lightning.com/2018/09/how-to-use-map-in-lightning-component.html
Ajinkya DhasAjinkya Dhas
Learn From Basics Salesforce Apex Collection: List ☁️⚡️
(Learn. Help. Share.) - https://www.salesforcekid.com/2019/04/salesforce-apex-collection-list.html
raj_sfdccraj_sfdcc
Hi Vijay,

Collections are more helpful when you are dealing with bulk records .

Below post can explains more basics of collections in salesforce .

Salesforce Collections with example (https://salessforcehacks.blogspot.com/2020/01/collections-in-salesforce-list-set-map.html)
manu manu 23manu manu 23
Hi, 

Assume maps as dictionary, where you will get all the related words based on the alphabets. In the same way the maps in salesforce works. To avoid the governor limits maps are the important tool especially in triggers. 

Differene between maps and lists are:
In lists you have to use for loop, using for loop and iterating all the records just to search for one record or more records that met the criteria is ridiculous, which increases the cpu time. 

In maps, we have key and value pair where if you give key, you get the reated value directly without any looping concepts(when you know the key)