How to Return Map Result from SOQL Query in Salesforce Apex

In Salesforce Apex, returning a Map from the SOQL query helps in accessing and handling the data in our Salesforce org. In Salesforce, Map is a data structure that allows you to store key-value pairs, making it easier to fetch records based on specific key values.

In this Salesforce tutorial, I will explain all possible methods to return map results from SOQL queries in Salesforce Apex.

Return Map Result from SOQL Query in Salesforce Apex

In Salesforce, the common use case to return a map is fetching a record by ID and grouping the records by standard fields.

Now, we will see a different example of returning a Map from an SOQL query.

Map of Records by ID

The common use case is where the key is the record ID, and the value is the record itself.

The class methods below will query account records and return the results as a map. The output will be a Map where the key is the ID, and the value is the Account record.

1. Navigate to the developer console, create a new Apex class from File > New > Apex class, and enter the code below.

public class AccountService {
    public static Map<Id, Account> getAccountsByIds(Set<Id> accountIds) {
        Map<Id, Account> accountMap = new Map<Id, Account>([
            SELECT Id, Name, Industry, Phone
            FROM Account
            WHERE Id IN :accountIds
        ]);

        return accountMap;
    }
}

2. Now, test the method by using the test class method below.

@isTest
private class AccountServiceTest {
    @isTest
    static void testGetAccountsByIds() {

        Account acc1 = new Account(Name = 'Test Account 1');
        Account acc2 = new Account(Name = 'Test Account 2');
        insert new List<Account>{acc1, acc2};

        // Calling the map method
        Map<Id, Account> result = AccountService.getAccountsByIds(new Set<Id>{acc1.Id, acc2.Id});

        System.assertEquals(2, result.size());
        System.assertEquals('Test Account 1', result.get(acc1.Id).Name);
    }
}

3. Run the test class by clicking on the Run button at the upper right side of the screen.

If the test method ran successfully, it will show in the Tests tab of the developer console.

Salesforce SOQL get output in Map

As we can see, the test method ran successfully. This way, we can return the map in results using SOQL in Salesforce Apex.

Test code with Anonymous window

Then, another method to test the method that returns the results in the map is to execute the code below in the Apex anonymous window.

Launch the anonymous window using “Ctrl+E,” then enter the code below and execute it.

Set<Id> accountIds = new Set<Id>{'0015i00000lU1hsAAC', '0015i00000v5rIRAAY'};
Map<Id, Account> accountMap = AccountService.getAccountsByIds(accountIds);
System.debug(accountMap);

In the input, I entered the Account ID and called the method AccountService.getAccountByIds. Then, in the debug window, you will see the mapped values of the Account IDs.

Get Map values in output in Salesforce SOQL

This way, we can return the map results from the SOQL Query in Salesforce Apex by mapping the records by ID.

Group Records by field

We may need to group records by a specific field. For example, grouping contacts by their account.

The method in the below Apex class contains methods to group Contact records by their associated AccountId.

The method will iterate over the fetched contacts and group them into a Map<Id, List<Contact>>, where the key is the AccountId and the value is a list of contacts.

1. In the developer console, create a new Apex class and execute the code below.

public class ContactService {
    public static Map<Id, List<Contact>> getContactsGroupedByAccount(Set<Id> accountIds) {
        // Initialize an empty map to hold the grouped results
        Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>();
        List<Contact> contactList = [
            SELECT Id, Name, Email, AccountId
            FROM Contact
            WHERE AccountId IN :accountIds
        ];

        for (Contact con : contactList) {
            if (!contactMap.containsKey(con.AccountId)) {
                contactMap.put(con.AccountId, new List<Contact>());
            }
            contactMap.get(con.AccountId).add(con);
        }

        return contactMap;
    }
}

In the output, it will return a Map where the key is AccountId and the value is a list of Contact-related records to that account.

2. Now, to test the code, we will create a test class, and for that, again, create an Apex class and enter the code below.

@isTest
private class ContactServiceTest {
    @isTest
    static void testGetContactsGroupedByAccount() {
        Account acc = new Account(Name = 'Test Account');
        insert acc;

        Contact con1 = new Contact(FirstName = 'Adam', LastName = 'Smith', AccountId = acc.Id);
        Contact con2 = new Contact(FirstName = 'Jenny', LastName = 'Williams', AccountId = acc.Id);
        insert new List<Contact>{con1, con2};

        Map<Id, List<Contact>> result = ContactService.getContactsGroupedByAccount(new Set<Id>{acc.Id});

        System.assertEquals(1, result.size());
        System.assertEquals(2, result.get(acc.Id).size());
    }
}

3. To run the test method, click on Test > New run, select the test class we created, and click on the Run button.

Return Map as output in Salesforce SOQL

If you see the success message after the test run, it means the class method is working fine.

Salesforce SOQL get output in Map

This way, we return a map result from the SOQL query in Salesforce Apex by grouping the records by field.

Adding Custom Keys for Map

To return map results, we can also use fields other than IDs as keys in the map. For instance, creating a map of accounts keyed by their unique field, such as AccountNumber.

The for loop in the method below will iterate over the queried records. Then, each queried record will be added to the Map with its AccountNumber as the key and the account record itself as the value.

1. To use custom keys in the map, create a new apex class and follow the code below.

public class AccountService {
    public static Map<String, Account> getAccountsByAccountNumber(Set<String> accountNumbers) {
        Map<String, Account> accountMap = new Map<String, Account>();

        List<Account> accounts = [
            SELECT Id, Name, AccountNumber, Industry
            FROM Account
            WHERE AccountNumber IN :accountNumbers
        ];
        for (Account acc : accounts) {
            accountMap.put(acc.AccountNumber, acc);
        }
        return accountMap;
    }
}

2. To test the class method, execute the code below in the Apex anonymous window.

Account acc1 = new Account(Name = 'Test Account 1', AccountNumber = 'ACC123', Industry = 'Technology');
Account acc2 = new Account(Name = 'Test Account 2', AccountNumber = 'ACC456', Industry = 'Finance');
insert new List<Account>{acc1, acc2};

Set<String> accountNumbers = new Set<String>{'ACC123', 'ACC456'};

Map<String, Account> accountMap = AccountService.getAccountsByAccountNumber(accountNumbers);
System.debug(accountMap);
}
Get mapped values of record fields in Salesforce SOQL

This way, we can use custom keys in SOQL and return them in the output as a Map in Salesforce Apex.

Map Values using the map.keySet() Method

In Salesforce SOQL, the map.keySet() method returns a set containing all the keys in the map. It associates the specified value with the specified key on the map.put() or map.putall(), which copies all of the mappings from the specified map to the original map.

In the example below, I will execute the map.keySet() method in the Apex anonymous window.

Map<String, String> accountIdNameMap = new Map<String, String>();

accountIdNameMap.put('0011A00000Xyz123', 'LT refineries');
accountIdNameMap.put('0011A00000Abc456', 'Dublin macines');
accountIdNameMap.put('0011A00000Def789', 'Burlington textiles');

Set<String> accountIdSet = new Set<String>();
accountIdSet = accountIdNameMap.keySet();

System.debug('Account IDs: ' + accountIdSet);
for (String accId : accountIdSet) {
    System.debug('Processing Account ID: ' + accId);
}

In the above method, we have used the method map.put(), we have added account IDs with their names to the map.

Output as a map:

After executing the anonymous code, we get the following output as values mapped with IDs.

Keyset method to map values in Salesforce Apex

This way, we can get a set containing all of the keys in the map in Salesforce Apex using the Keyset().map method.

Conclusion

In this Salesforce tutorial, we learned the methods used in the above examples to return a map result from SOQL Query in Salesforce Apex. In the examples, we returned the output in a map by mapping the records by ID, fields, and custom key values.

We also returned a map of values using the method map.keySet(), in which we used the map.put() method to add records and return all sets of keys in a map.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.