Sub topic 9
Collections of SObjects
This chapter assumes you know List, Set, and Map basics, can read a simple SOQL query, and have used DML statements such as insert and update. It covers what changes when the elements are records instead of strings or numbers.
Why SObject collections matter
An SObject is any Salesforce record type, such as Account, Contact, or MyObject__c. Most Apex code reads records into a collection, changes them, and saves them with one DML statement. The collection holds references to record objects, not copies of their data. That fact explains most of the behavior in this chapter.
Lists of SObjects
A list typed with a concrete SObject, such as List<Account>, is the most common structure. A SOQL query returns one directly, and DML statements accept one directly.
List<Account> accounts = [
SELECT Id, Name, Rating
FROM Account
WHERE Rating = null
LIMIT 200
];
for (Account a : accounts) {
a.Rating = 'Warm';
}
update accounts;The loop variable a points at the same record object that sits in the list. Changing a.Rating changes the list element, so no write-back step is needed before the update.
You can also build a list of new records in memory:
List<Contact> newContacts = new List<Contact>();
for (Integer i = 0; i < 3; i++) {
newContacts.add(new Contact(LastName = 'Tester ' + i));
}
insert newContacts;After insert, each record in the list has its Id populated. You can use those Ids immediately, for example to create child records.
Maps keyed by Id
The Map constructor accepts a list of records and keys each one by its Id. The key and value types must match the query: Map<Id, Account> for a list of Account.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 50]
);
Account one = accountsById.values()[0];
System.debug(accountsById.containsKey(one.Id)); // trueThis constructor has three requirements:
- Every record must have an
Id. A list of unsaved records fails, so build those maps by hand or insert first. - If two records share an Id, the later one replaces the earlier one.
- The value type must be the specific SObject type. The constructor does not accept a list of mixed types.
The map's values() method returns a list of the same record references stored in the map. Editing those records edits the map's contents too:
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Id, Description FROM Account LIMIT 50]
);
for (Account a : byId.values()) {
a.Description = 'Reviewed';
}
update byId.values();Keep keys as Id, not String
Salesforce Ids exist in a 15-character, case-sensitive form and an 18-character, case-safe form. A Map<Id, ...> treats both forms as the same key. A Map<String, ...> does not. If you key by String and look up with a different length, get returns null with no error.
A lookup pattern: Set, Map, and one DML
The usual workflow has three steps. Collect Ids into a set, query related records once into a map, then use the map inside a loop.
List<Contact> contacts = [
SELECT Id, AccountId
FROM Contact
WHERE AccountId != null
LIMIT 200
];
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
accountIds.add(c.AccountId);
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account parent = accountsById.get(c.AccountId);
if (parent != null) {
c.Description = 'Works at ' + parent.Name;
}
}
update contacts;The set removes duplicate Ids, so the second query's IN clause stays small. The map turns a per-record query into a constant-time lookup. The null check handles a parent the user cannot see or that was deleted.
Choosing a structure for records
| Need | Structure | Notes |
|---|---|---|
| Process or save records in order | `List<Account>` | Accepted directly by DML |
| Track which records were seen | `Set<Id>` | Unique, cheap to build, safe to use in `IN` |
| Find a record by Id | `Map<Id, Account>` | Build from a query or list |
| Deduplicate whole records | Avoid `Set<SObject>` | See the next section |
Why Set<SObject> is risky
Apex allows Set<Account>, but it decides whether two records are equal by comparing their type and field values, not their identity. The consequences are:
- Two separate
Accountobjects with identical field values count as one element. - If you change a field after adding the record to a set, the set can no longer reliably find it. The same applies to using a record as a map key.
Generic SObject lists
List<SObject> can hold records of different types. This is useful for generic helpers and for saving several object types in one DML call.
List<SObject> toSave = new List<SObject>{
new Account(Name = 'Acme'),
new Contact(LastName = 'Rivera')
};
insert toSave;
for (SObject s : toSave) {
System.debug(s.getSObjectType() + ' ' + s.get('Id'));
}On a generic SObject, you read and write fields with get('FieldName') and put('FieldName', value). The field name is checked at run time, so a typo throws an exception instead of failing at compile time. Cast to the concrete type when you need compile-time checks:
Account acc = (Account) toSave[0];
acc.Name = 'Acme Corp';A List<SObject> returned by a query can be cast to a concrete list type, such as (List<Account>) rawList, when the records are all that type.
Mixed-type lists have a DML cost. Salesforce processes a mixed list in chunks that group records by type. A list that alternates between types creates many chunks, and a single DML statement can process at most 10 chunks. Sort such a list by type before saving.
Common errors
- Duplicate Id in one
updatelist. Putting the same record, or two records with the same Id, in a list passed toupdatethrows "Duplicate id in list". Build aMap<Id, Account>first and callupdate map.values(), so each Id appears once. - Reading a field you did not query.
SObjectException: SObject row was retrieved via SOQL without querying the requested fieldmeans theSELECTomitted a field you read. Add it to the query. - Building a map from unsaved records. The Id is
nulluntil afterinsert. - Copying the list, not the records.
List<Account> b = a;makes two names for one list. Aclone()of the list still shares the same record objects. The later chapter on references coversdeepClone.
Exercise
A trigger collects List<Contact> contacts and needs each contact's parent Account name. Write the steps, in order, that read the parent names with exactly one extra query and no query inside a loop. Then say what type each lookup key should have and why.
Show answer
First, loop over contacts and add each non-null AccountId to a Set<Id>. Second, run one query, SELECT Id, Name FROM Account WHERE Id IN :accountIds, and pass the result to the constructor of a Map<Id, Account>. Third, loop over contacts again and call accountsById.get(c.AccountId), checking for null before using the result. The key type should be Id, not String, because an Id key treats the 15-character and 18-character forms of the same Id as equal, while a String key would miss.