0

What syntax is needed to add multiple List of Sobjects to an array? I have this code currently in a batch class:

public List<Contact> start(Database.BatchableContext bc) {
  List<Contact> contactList1 = ExternalAPI.getDataset(APIKey1__c);
  List<Contact> contactList2 = ExternalAPI.getDataset(APIKey2__c);
  List<Contact> contactList3 = ExternalAPI.getDataset(APIKey3__c);
  return contactList1;
}

What I am trying to do is return an array that contains all 3 list. I know my return type on the method will need to change and the return statement itself, but I am not sure what syntax to use to return I guess what would be an array of Sobjects?

I think I need something more like the below (psuedo-code), but I do not believe this will work as expected:

public List<Contact> start(Database.BatchableContext bc) {
  contactArray = [];
  List<Contact> contactList1 = ExternalAPI.getDataset(APIKey1__c);
  List<Contact> contactList2 = ExternalAPI.getDataset(APIKey2__c);
  List<Contact> contactList3 = ExternalAPI.getDataset(APIKey3__c);
  contactArray.add(contactList1);
  contactArray.add(contactList2);
  contactArray.add(contactList3);
  return contactArray;
}
2

You use the addAll method instead:

  contactArray = new List<Contact>();
  List<Contact> contactList1 = ExternalAPI.getDataset(APIKey1__c);
  List<Contact> contactList2 = ExternalAPI.getDataset(APIKey2__c);
  List<Contact> contactList3 = ExternalAPI.getDataset(APIKey3__c);
  contactArray.addAll(contactList1);
  contactArray.addAll(contactList2);
  contactArray.addAll(contactList3);
  return contactArray;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.