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
Parteek Goyal 3Parteek Goyal 3 

Why we use map in salesforce?

Hi All,

I want to know that why we use map instead of list in salesforce. Please help with scenario.

Thanks,
Parteek

Best Answer chosen by Parteek Goyal 3
Amit Chaudhary 8Amit Chaudhary 8
Please check below posy for same
1 ) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html
2 ) http://www.salesforcegeneral.com/salesforce-articles/using-an-apex-map-with-a-list-of-sobjects.html

User-added image

Example 1:-  Using trigger populate the Account Field on the Contact record (only insert scenario)

If we use List and not Map
Apex Class
trigger ContactTriggerWithList on Contact (before insert) 
{
Set<Id> SetAccountId = new Set<Id>(); // Use set to collect unique account ID

for(Contact con: Trigger.new) 
{
 if(con.AccountId != null) 
 {
  SetAccountId.add(con.AccountId); // add Account in Set
 }
}

if( SetAccountId.size() >0 ) 
{
 List<Account> listAccount = [ Select Id, Name, Type from Account where Id IN :SetAccountId ]; // Query Related Account
 
 for(Contact con: Trigger.new) 
 {
  if(con.AccountId != null)
  {
   for(Account acc: listAccount)
   {
    if(con.AccountId == acc.Id)
    {
     con.Type__c = acc.Type;
    }
   }
  }
 }
} 
}


NOTE:- In this we are using List of Accounts, Where we have to loop through the matching Account every time to populate the Type__c in the second for loop. In this case need to use nested loop.
To Above the Nested Loop We can use the Map .

Same Trigger using the Map:
trigger ContactTriggerWithMap on Contact (before insert) 
{
    Set<Id> SetAccountId = new Set<Id>();
    for(Contact cont: Trigger.new) 
 {
        if(cont.AccountId != null) 
  {
            SetAccountId.add(cont.AccountId);
        }
    }
    
    if(SetAccountId.size() > 0 ) 
 {
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
        for(Contact cont: Trigger.new) 
  {
            if(cont.AccountId != null && mapAccount.containsKey(cont.AccountId) ) 
   {
                cont.Type__c = mapAccount.get(cont.AccountId).Type;
            }
        }
    }
}

NOTE:- Here we are using map of Account so we can directly use the Map to get the Account record. No need of 2nd for loop here
 

All Answers

Anwarul HaqueAnwarul Haque
Use Maps to navigate across Lists!

https://youtu.be/jMQKRXVIubM
Jasper WallJasper Wall
Hi,
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>

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.

Scenarios:
1) When moving line items from one opportunity to other opportunity we need to use map
2) to determine whether an old value is changed or not in a trigger we need to use map

Lists is not suitable for above scenarios.

Let us know if it helps,

Thanks,
Balayesu
Anilkumar KotaAnilkumar Kota
Hi Parteek,

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>

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>

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. For example, the following table represents a map of countries and currencies

Find below link for Detailed explanation regarding collections.

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections.htm

https://www.sundoginteractive.com/blog/apex-why-maps-are-your-friend
Ramssf70Ramssf70
Hi prateek,
Maps are my favorite collection types .The Reason why its very essential to use Maps in apex  classes or triggers is it makes life simple for writing bulkified apex class or trigger .
Apex we all know runs on an multitenant  architecture .The resources are shared and hence we have governor limits in apex .The advantages of proper usage of maps will help  to  reduce script statements,No of queries for a single context of class or trigger execution,avoiding query on a single object twice .

As a fresher to salesforce  we are unaware of various techniques that we can employ to reduce the script statements and reduce heap size of collection like Lists,Maps and Sets
If you have been coding in apex from long time you might  have come across common use case that you need to aggregate collection of child records grouped by ParentId.

Something like say i will query on Contact Object and i am retrieving all contacts and I need a collection Map of Parent Id (AccountId) as Key and the collection of contacts related to AccountId .In short in apex language terms Map<AccountId,List<Contacts>>

Here is the code that i have included as an example on how to form the collection of Map<Id,List<Contact>>
Map < Id, List < Contact >> mapAccIdByCntlst = new Map < Id, List < Contact >> ();

for (Contact c: [Select Id, name, AccountId from Contact where AccountId != null]) {

        // AccountId mapping with Contact List

        if (mapAccIdByCntlst.containsKey(c.AccountId)) {
                mapAccIdByCntlst.get(c.AccountId).add(c); //tricky part .Here map.get(key) is returning list and we are adding contacts to the list
        } else {
                List < Contact > lstcnts = new List < Contact > (); //Initialize list as no key is found before and first time we get key 
                lstcnts.add(c);
                mapAccIdByCntlst.put(c.AccountId, lstcnts);
        }

}

 
Amit Chaudhary 8Amit Chaudhary 8
Please check below posy for same
1 ) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html
2 ) http://www.salesforcegeneral.com/salesforce-articles/using-an-apex-map-with-a-list-of-sobjects.html

User-added image

Example 1:-  Using trigger populate the Account Field on the Contact record (only insert scenario)

If we use List and not Map
Apex Class
trigger ContactTriggerWithList on Contact (before insert) 
{
Set<Id> SetAccountId = new Set<Id>(); // Use set to collect unique account ID

for(Contact con: Trigger.new) 
{
 if(con.AccountId != null) 
 {
  SetAccountId.add(con.AccountId); // add Account in Set
 }
}

if( SetAccountId.size() >0 ) 
{
 List<Account> listAccount = [ Select Id, Name, Type from Account where Id IN :SetAccountId ]; // Query Related Account
 
 for(Contact con: Trigger.new) 
 {
  if(con.AccountId != null)
  {
   for(Account acc: listAccount)
   {
    if(con.AccountId == acc.Id)
    {
     con.Type__c = acc.Type;
    }
   }
  }
 }
} 
}


NOTE:- In this we are using List of Accounts, Where we have to loop through the matching Account every time to populate the Type__c in the second for loop. In this case need to use nested loop.
To Above the Nested Loop We can use the Map .

Same Trigger using the Map:
trigger ContactTriggerWithMap on Contact (before insert) 
{
    Set<Id> SetAccountId = new Set<Id>();
    for(Contact cont: Trigger.new) 
 {
        if(cont.AccountId != null) 
  {
            SetAccountId.add(cont.AccountId);
        }
    }
    
    if(SetAccountId.size() > 0 ) 
 {
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
        for(Contact cont: Trigger.new) 
  {
            if(cont.AccountId != null && mapAccount.containsKey(cont.AccountId) ) 
   {
                cont.Type__c = mapAccount.get(cont.AccountId).Type;
            }
        }
    }
}

NOTE:- Here we are using map of Account so we can directly use the Map to get the Account record. No need of 2nd for loop here
 
This was selected as the best answer
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
Nandhini s 11Nandhini s 11
Hi,

I know this is an old thread but can someone clear this for me.
In the below, what's stored in key and what's stored in value?

Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
raj_sfdccraj_sfdcc
Hi Nandhini,

There might be a situation you require to deal with parent and child records ,Map can provide great help in those situations .

Below post can provide you idea of collections with examples .

Collections in Salesforce (https://salessforcehacks.blogspot.com/2020/01/collections-in-salesforce-list-set-map.html)
sofiya jainsofiya jain
Apple has been slowly but steadily rolling out the new mapping data everywhere in the U.S.However, a steady-functioning mobile map experience is quite precise map data. So you'll now receive stunning new features with the newest iOS 13. 
Creating Favorite Locations on the iPad & iPhone 
If you would like to make some favorite locations on the iPad and iPhone, then you would like to follow the instructions given below. geek squad support
Adding a Location: 
  • First of all, attend the Maps application on your device. 
  • Then you ought to move to the right-hand side, and tap on the (+)add icon beneath Favorites. 
  • You have to travel to the search box and enter the situation beneath Add Favorite. you'll input a reputation or address. Also, you'll select the Siri icon to look through your voice. 
  • You can choose a location by selecting the “+add” icon for an area beneath Siri Suggestion. 
  • You should select the (+) add icon to upload the situation . 
  • Go to the small print screen and modify the situation title, if you'd wish to. 
  • Thereafter choose the sort of location. 
  • Navigate to the Add Person beneath Share ETA, if you'd wish to share the situation with anyone where you've got traveled to the favorite location.  mcafee.com/activate
You should tap on Done at the upper right-hand side of the display to save lots of the Favorites. 
Remove Favorites: 
  • Get started by getting to the Maps application and choose “See All” option near the Favorites section. 
  • Then you ought to select the small print icon to the right-hand side of the situation you'd wish to remove.
  •  Go to the lower side and choose the Remove Favorite option. 
Creating Collections within the New Maps Application.
Follow the steps mentioned below if you would like to make collections within the new Maps application. Creating a Collection: 
  • Then you ought to choose “See All” to the right-hand side of the collections.
  •  Go to the lower right-hand side and choose +add icon. 
  • Now, tap on Create option. 
Adding Locations to a Collection: 
  • To begin with, attend the newly created Collection on your device. 
  • Then you ought to choose the “Add a Place” option. 
  • Navigate to the search bar and enter your location to look it. 
  • You have to pick the +add icon near the situation you'd wish to add.
  •  If you would like to feature more locations, then repeat this procedure. 
  • Now, once you are done, select Done.mcafee.com/activate
Exploring the gathering Locations: 
  • First, you've got to pick a location to understand more about it. 
  • This should be available beneath the gathering . Then you ought to select Flyover. 
  • You have to pick Directions to locate the way to get to the situation. 
  • Navigate to the most location page. 
  • Check the small print taken from either Wikipedia or TripAdvisor. 
  • Or choose “Create New Contact” on the bottom of the situation .
  •  Or you should “Add to Existing Contact”. 
  • Or you can “Report an Issue” when having a problem together with your location listing. 
  • Navigate to the top of the display near the situation , and you'll select “Add to contain the situation in other Collection. 
  • Now, select the Share choice to share the situation details with others via Mail or Messages or the other application on the device. 
Delete Locations from the Collection: 
  • You should attend the lower side of the collections screen in Maps, and choose the Edit option. 
  • Then you've got to pick the circle to the left-hand side of the situation you'd wish to remove. 
  • Now, to erase the situation from the gathering, select the Delete option
  • You can read my blog with a click on the button above. how to login to Linksys router 

Howdy, I’m Sara. I’m a web developer living in the USA. I am a fan of design, technology, and music. I’m also interested in photography and programming. You can read my blog with a click on the button above.