Activity Forums Salesforce® Discussions What is the use of mapping in Salesforce?

  • Anurag

    Member
    August 8, 2018 at 1:08 pm

    Hi Prachi,

    We need mapping (using 'map' collection) basically to map 2 things which can be anything i.e. sObject, primitive data types and even collections. But the advantage of using map is that it saves us from using the for loop.

    Let us understand this by an example:

    Suppose we have 10,000 Account records and we need to have a set of IDs of all those records.

    Without Map:

    List<account> acc = [select Id from account limit 10000] ; 

    set<id> accIds = new set<id>() ; 
    for(Account a: acc) 

     accIds.add(a) ; 

    Thus, the loop runs 10000 times fetching us the required IDs.

    With Map:

    Map<id,account> m = new Map<id,account>([Select Name from Account limit 10000]); 

    Set<Id> s=m.keyset();

    The query maps the Account Id with the field that we have passed (in this case- 'Name') in the variable 'm'.

    Thus, we are saved with the tedious loop method.

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos