You need to sign in to do that
Don't have an account?

map
Hello All,
i am new to salesforce. i am not getting how to start with map and how to deal wirh map, wheen should use map and how to use map in apex. so please guide about map .
i am new to salesforce. i am not getting how to start with map and how to deal wirh map, wheen should use map and how to use map in apex. so please guide about map .
Map is a collection of key-value pairs where each unique key maps to a single value,
here is an exapmle of triggers that updates a Contact Owner with the Account Owner before updating Account,
Account is a Lookup on Contact Object.
trigger accountowner on Account (before update) {
map<id,id> mp=new map<id,id>();
for(Account ac:Trigger.new){
mp.put(ac.id,ac.OwnerId);
}
list<contact> con=new list<Contact>();
for(contact ac:[Select id,Ownerid,accountid from Contact where Accountid=:mp.keySet()]){
con.add(new contact(id=ac.id,ownerid=mp.get(ac.accountid)));
}
update con;
}
thanks
Ashish
Hi,
map is very important in salesforce.many times you can use it to avoid unnecessary SOQL Queries saving governer limit.
like this query:
map<id,account> accountMap=new map<id,account>([select id,name from account]);
will store accounts data, with account id as key and Record as value. you can easily retrieve any account anywhere in code by usung map methods if you know account id.
For Map class read here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm
1) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html
Map : A map is a collection of key-value pairs
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>();
Map<Integer, String> mapOfString = new Map<Integer, String>(); mapOfString.put(1, 'Amit'); mapOfString.put(2, 'Rahul'); System.assert(mapOfString.containsKey(1));
String value = mapOfString.get(2);
System.assertEquals('Rahul', value); Set<Integer> s = mapOfString.keySet();
Map<String, String> myMap = new Map<String, String>{'a' => 'b', 'c' => 'd'};
Example 1:- Using trigger populate the Account Field on the Contact record (only insert scenario)
If we use List and not Map
Apex Class 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:
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