Skip to content

Instantly share code, notes, and snippets.

@johnhutchins
Last active April 26, 2019 22:11
Show Gist options
  • Save johnhutchins/6e03b048027df751188feb9890cb9ef2 to your computer and use it in GitHub Desktop.
Save johnhutchins/6e03b048027df751188feb9890cb9ef2 to your computer and use it in GitHub Desktop.
public with sharing class MapExercises {
// Given a list of Accounts, create and return a map where the KEY is the Account Id and the values are the Account
public static Map<Id, Account> getAccountMap(Account[] accs){
Map<Id, Account> accounts = new Map<Id, Account>();
for (Account ac : accs){
accounts.put(ac.Id, ac);
}
//System.debug('Get Account map from passed in data accounts === ', accs);
return accounts;
}
// Given a list of Contacts, create and return a map where the KEY is an `Contact.Id` and the values are the related Account (`Contact.Account`)
public static Map<Id, Account> getAccountByContactId(Contact[] cts){
Map<Id, Account> contacts = new Map<Id,Account>();
for (Contact c : cts){
contacts.put(c.Id, c.Account);
}
return contacts;
}
// Given a list of Contacts, create and return a
//map where the KEY is an Account Id and the values are the list of contacts Associated to that account
// (via `contact.AccountId`)
public static Map<Id, Contact[]> groupContactsByAccountId(Contact[] contacts){
Map<Id, List<Contact>> generatedMap = new Map<Id,List<Contact>>();
for (Contact rc : contacts){
//if generatedMap already contains the Account Id, add the contact to the list.
if (generatedMap.containsKey(rc.AccountId)){
generatedMap.get(rc.AccountId).add(rc);
} else { //Otherwise create a new list with the current contact
generatedMap.put(rc.AccountId, new List<Contact>{rc});
}
}
return generatedMap;
}
// Given a list of Accounts, create and return a map where the KEY is an `Account.Type` and the values the SUM of the account AnnualRevenue
public static Map<String, Decimal> getAccountRevenueBySum(Account[] accs){
if (accs == null){
return null;
} else {
Map<String,Decimal> accountMap = new Map<String,Decimal>();
for (Account a : accs){
if (accountMap.containsKey(a.Type)){
accountMap.put(a.Type, accountMap.get(a.Type) + a.AnnualRevenue);
} else {
accountMap.put(a.Type, a.AnnualRevenue);
}
}
return accountMap;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment