Sub topic 9
Collections of SObjects
This chapter assumes you know the basics of List, Set, and Map, can read SOQL, and know what an SObject such as Account or Contact is. Here you will see how collections behave when they hold records.
Lists as the unit of work
DML statements (insert, update, delete) accept a list. One statement then handles many records and counts as a single DML statement against the governor limit. Build the list first, then run DML once, outside any loop.
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 3; i++) {
accounts.add(new Account(Name = 'Acme ' + i));
}
insert accounts;
System.debug(accounts[0].Id != null); // trueAfter insert, Apex writes the new Ids back into the same record objects in the list. You don't need to query them again.
Generic SObject lists
List<SObject> can hold records of different types. Use it when the code doesn't know the concrete type ahead of time.
List<SObject> records = new List<SObject>{
new Account(Name = 'Globex'),
new Contact(LastName = 'Lee')
};
for (SObject r : records) {
System.debug(r.getSObjectType()); // Account, then Contact
}Read fields through get('FieldName'), or cast to the concrete type first, such as (Account) r.
Records are references
A list or map of SObjects stores references to record objects, not copies. Two collections built from the same records share them. A change made through one collection shows up in the other.
Map<Id, Account> byId = new Map<Id, Account>(accounts);
byId.get(accounts[0].Id).Name = 'Renamed';
System.debug(accounts[0].Name); // Renamed
update accounts;The Map constructor takes a list of SObjects and uses each record's Id as the key. The records must already have Ids, so run the insert first.
Common pitfalls
- Duplicate Ids in one DML list. Adding the same record to an
updatelist twice fails with a "Duplicate id in list" error. Collect records in aMap<Id, SObject>instead. A secondputwith the same Id replaces the first entry, so each record appears once. - Keying a map before insert. Records that haven't been inserted have a null
Id. Keys built from them are all null, and the entries overwrite each other. - Using
Set<SObject>. A set of SObjects compares records by field values, not by Id. Changing a field after adding a record can break lookups. UseSet<Id>to track which records you have seen. - Mixing types in DML. A mixed
List<SObject>can be used in DML, but it is easier to debug and less likely to hit chunking limits if you keep one type per list.
Collecting Ids from records
A common step before a query is to turn a list of records into a set of Ids.
Set<Id> accountIds = new Set<Id>();
for (Account a : accounts) {
accountIds.add(a.Id);
}Because the Ids are unique, the set also removes any duplicates that come from repeated records. The next chapter uses this kind of set as a bind variable in SOQL.
Exercise
A trigger builds a List<Contact> for an update. Two code paths each add the same Contact record to the list, and the update fails with "Duplicate id in list". How can you change the collection so each record is updated once?
Show answer
Collect the contacts in a Map<Id, Contact> and call put(contact.Id, contact) in both paths. A repeated Id replaces the earlier entry, so the map holds each record once. Then run update on contactsMap.values().