How to Access Query Results (SOQL) Values using MAP in Apex Class?

For Example:

This is a After Trigger in Account:
for (Account acc : Trigger.new) {
accId.add(acc.Id);
}
map<Id, Contact> mapContacts = new map<Id, Contact>([Select Id, FirstName, LastName, RecordTypeId, AccountId, Email, Fax from Contact where AccountID =: accId]);

ssing above approach, the Results in your Map being keyed by the Id (Contact ID) field not for the other contact values like firstname, lastname, etc.

You need to populate your Map using the otehr than Id then we need do to manually by iterating over the results of the query like below method:
Another Way:
map<Id, Contact> mapContacts = new map<Id, Contact>();
list<Contact> listContacts = new map<Id, Contact>([Select Id, FirstName, LastName, RecordTypeId, AccountId, Email, Fax from Contact where AccountID =: accId]);

if(!listContacts.isEmpty()){
for(Contact con: listContacts) {
mapContacts.put(con.Id, con);
}
}

using this way after queried the data in the list and need to loop thr each contacts data and put it the each data into the map (mapContacts) with Key (Contact Id) & Values (Contact Results)

For More information related to Map, please click the below link for salesforce doc:

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_map.htm

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *

*