Activity Forums Salesforce® Discussions How to return Map result from SOQL query in Salesforce Apex? Reply To: How to return Map result from SOQL query in Salesforce Apex?

  • Parul

    Member
    September 22, 2018 at 5:44 pm

    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