Activity › Forums › Salesforce® Discussions › How to return Map result from SOQL query in Salesforce Apex?
Tagged: Account ID, Apex Map, Apex SelectList, Opportunity ID, Salesforce Accounts, Salesforce Apex, Salesforce Apex Code, SOQL Query
-
How to return Map result from SOQL query in Salesforce Apex?
Posted by Aman on September 22, 2018 at 5:03 PMHow to return Map result from SOQL query in Salesforce Apex?
Parul replied 7 years, 7 months ago 3 Members · 2 Replies -
2 Replies
-
Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);
- [adinserter block='9']
-
You can perform this operation by going through this code given below:
//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;//Fetching all accounts
List<account> accList = new List<Account>();//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>([select Id,name,site,rating,AccountNumber from account limit 50000]);//getting list of account using map.values method
accList = accountIdObjMap.values();//getting set of account Id’s using map.keySet method
accIdsSet = accountIdObjMap.keySet();//getting list of account Id’s using list.addAll method
accIdsList.addAll(accIdsSet);To clarify, this method can only be used to generate Maps using Id of the object you are querying as the key. If you want to use a different value as the key, you will have to iterate over the list returned by your query and put values into a Map. For instance, if you wanted to use AccountId as the key, you would need to do something like this: List<Opportunity> oppList = [Select Id, AccountId from Opportunity]; Map<Id,Opportunity> accOppMap = new Map<Id,Opportunity>(); for(Opportunity o : oppList){ accOppMap.put(o.AccountId,o); }
Hope this may help
-
This reply was modified 7 years, 7 months ago by
Parul.
-
This reply was modified 7 years, 7 months ago by
Log In to reply.