fork download
  1. List<Account> accs = [SELECT Id, Name FROM Account LIMIT 5];
  2.  
  3. // Query all Contacts in one go
  4. Map<Id, List<Contact>> accToContacts = new Map<Id, List<Contact>>();
  5.  
  6. for (Contact c : [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId IN :accs]) {
  7. if (!accToContacts.containsKey(c.AccountId)) {
  8. accToContacts.put(c.AccountId, new List<Contact>());
  9. }
  10. accToContacts.get(c.AccountId).add(c);
  11. }
  12.  
  13. // Loop accounts safely
  14. for (Account acc : accs) {
  15. List<Contact> cons = accToContacts.get(acc.Id);
  16. System.debug('Contacts for ' + acc.Name + ': ' + (cons != null ? cons.size() : 0));
  17. }
  18.  
Success #stdin #stdout #stderr 0.02s 11052KB
stdin
Standard input is empty
stdout
Object: nil error: did not understand #associationAt:ifAbsent:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject(Object)>>doesNotUnderstand: #associationAt:ifAbsent: (SysExcept.st:1448)
DeferredVariableBinding>>resolvePathFrom: (DeferBinding.st:115)
DeferredVariableBinding>>value (DeferBinding.st:69)
UndefinedObject>>executeStatements (prog:7)
Object: nil error: did not understand #associationAt:ifAbsent:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject(Object)>>doesNotUnderstand: #associationAt:ifAbsent: (SysExcept.st:1448)
DeferredVariableBinding>>resolvePathFrom: (DeferBinding.st:115)
DeferredVariableBinding>>value (DeferBinding.st:69)
UndefinedObject>>executeStatements (prog:7)
stderr
./prog:1: parse error, expected ']'
./prog:7: expected expression
./prog:16: expected expression