+ Start a Discussion

Usage of Map function



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




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:




 retrieves a record from the map based on its id.





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


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





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


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



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


Thanks a lot Bob, Ramya.