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
r1985r1985 

Usage of Map function

Hi,

 

Anybody help me how to use the map function and the logic behind it using some sample code?

 

 

bob_buzzardbob_buzzard

A map allows you to associate a key with a value, with each key having a single value.  This allows you to retrieve the value based on the key without having to iterate all the objects looking for a match.

 

Its  an unordered collection, which means that if you iterate the values stored in the map you can't guarantee they will be returned in the same order that you put them in.

 

A good example of the use of maps is a before update trigger - in this case you have the old sobject values in Trigger.oldMap and the new sobject values in Trigger.newMap, both of which are maps of sobject keyed by id (i.e. an sobject can be looked up by its id).

 

This allows you to iterate the Trigger.newMap and when you find a record you are interested in, you can immediately access the equivalent from Trigger.oldMap without having to traverse all the records.  For example,

 

for (Account acc : Trigger.newMap.values())
{
   // is the account type 'Client'
   if (acc.type=='Client')
   {
      // check if it was previously something else
      if (trigger.oldMap.get(acc.id).type!='Client')
      {
         // take appropriate action when account type changes
      }
   }
}

 

This piece of code:

 

trigger.oldMap.get(acc.id)

 

 retrieves a record from the map based on its id.

 

 

 

r1985r1985

Also can u please explain abt the put and get methods of map?

bob_buzzardbob_buzzard

Put adds a key/value pair to the map.  So if I have a map that contains accounts and is keyed by id:

 

Map<Id, Account> accsMap=new map<Id, Account>();

Account acc=[select id, Name from Account limit 1];

accsMap.put(acc.id, acc);

 

Get retrieves the value based on the key, so to retrieve the account that I added to the map above:

 

Id accId=acc.id;

Account accFromMap=accsMap.get(accId);

 

 

 

RamyaKrishnaRamyaKrishna

get():- Retrieve the value from the key.

map<Integer,String> m1=new map<Integer,String>{1=>'N',2=>'H'};

system.debug('******* Result **********'+m1.get(2));

output: ****** Result **********H

 

 map<Integer,String> m1=new map<Integer,String>{1=>'N',2=>'H'};

system.debug('******* Result **********'+m1.get(4));

output: ****** Result **********null----------------------------

 

put():- Put the value at specified key location.

map<Integer,String> m1=new map<Integer,String>{1=>'N',2=>'H'};

m1.put(3,'Raju');

system.debug('**** Result ****'+m1.get(3));op: *** Result ****Raju

 

 

For more information regarding to this just read apex developer guide.

r1985r1985

Thanks a lot Bob, Ramya.