Use of Maps Data Collection in Apex (Part -2)

3. If map of <Id/String.etc,Decimal> is required and you need to sum/count all the child records –

Below is an example in Apex. It can be used to create a map to track the total opportunity amounts for each account. The key is the Opportunity Account Id’s. The value is the sum of all opportunities for the account.

/* Declaring a new map called totalOpportunitesAmountByAccount 
 * which uses an Account Id as the key and a Total Amount of all the opportunites 
 * associate with the account as the value*/
Map<Id,Decimal> totalOpportunitesAmountByAccount = new Map<Id,Decimal>();

// Query all Opportunity records and iterate through each one
for(Opportunity opp : [Select id, Amount, AccountId from Opportunity order by AccountId]) {
    // Retrieve the current total for this AccountId from the map
    Decimal currentTotal = totalOpportunitesAmountByAccount.get(opp.AccountId);
    // If there is no entry yet for this AccountId, initialize the total to 0
    if (currentTotal == null) {
        currentTotal = 0;
    }
    // Add the current Opportunity's Amount (or 0 if null) to the running total and update the map
    totalOpportunitesAmountByAccount.put(
        opp.AccountId, 
        currentTotal + (opp.Amount != null ? opp.Amount : 0)
    );
}

// Retrieve the total Opportunity Amount for a specific AccountId
Decimal totalOppAmount = totalOpportunitesAmountByAccount.get(AccountId);
4. If map of <Id/String.etc,List<Sobject/String>> is required –

Below is an example in Apex. It can be used to create a map of a list of contacts and Account Id. The key is Account Id. The value is a list of all the contacts associated with the Account.

/* Declaring a new map called contactsByAccount which uses an Account Id as the key 
 * and list of all the contacts associate with the Account as the value*/
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();

// Query all Contact records and iterate through each one
for (Contact con : [SELECT Id, Name, AccountId, FirstName FROM Contact ORDER BY AccountId]) {
    // Check if the map already contains a list for this AccountId
    if (!contactsByAccount.containsKey(con.AccountId)) {
        // If not, initialize a new list for this AccountId in the map
        contactsByAccount.put(con.AccountId, new List<Contact>());
    }
    // Add the current Contact to the list for this AccountId
    contactsByAccount.get(con.AccountId).add(con);
}

// Retrieve the list of Contacts associated with the given AccountId from the map
List<Contact> accountContacts = contactsByAccount.get(accountId);

// Check if the list of Contacts is not null (i.e., there are Contacts for this Account)
if (!accountContacts != null) {
    // Iterate through each Contact in the list
    for (Contact con : accountContacts) {
        // Access the FirstName field of the current Contact
        String firstName = con.FirstName;
    }
}

Leave a comment