The getSobjectListById()
method is a powerful utility function that can greatly simplify the task of grouping SObject
records by a specific field. By improving code performance and readability, this method can help you write more efficient and maintainable Apex code.
public static Map<Id, List<SObject>> getSobjectListById(String key, List<SObject> incomingList) {
Map<Id, List<SObject>> returnValues = new Map<Id, List<SObject>>();
for (SObject current : incomingList) {
if (current.get(key) != null) {
Id currentId = (Id) current.get(key);
if (!returnValues.containsKey(currentId)) {
returnValues.put(currentId, new List<SObject>());
}
returnValues.get(currentId).add(current);
}
}
return returnValues;
}
This utility function takes a field name (key) and a list of SObject
records as parameters. It returns a map where the keys are the unique IDs from the specified field, and the values are lists of SObject
records that have the same field value.
Let's consider a real-life scenario where getSobjectListById()
can be used. Suppose you are working on a Salesforce project where you need to send a customized email to each Account's Contacts. The email content is based on the specific Account's details.
First, you would query all the Contacts and their related Account details. Then, you would need to group these Contacts based on their AccountId. This is where getSobjectListById()
comes into play. You can use this method to create a map where the key is the AccountId and the value is a list of Contacts related to that Account.
Here's how you can do it:
List<Contact> contactList = [SELECT Id, Name, AccountId, Account.Name FROM Contact];
Map<Id, List<SObject>> accountContactsMap = Utils.getSobjectListById('AccountId', contactList);
Now, accountContactsMap
contains a list of Contacts for each AccountId. You can iterate over this map to send a customized email to each Account's Contacts.