Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
// Create an empty list of Accounts
List myList = new List();
Populating List from a SOQL query –
Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call.
// Create a list of account records from a SOQL query
List accts = [SELECT Id, Name FROM Account LIMIT 1000];
Add & Retrieve List elements and used for Bulk Processing-
You can use add() method to set sObject element to list and get() method to access from sObject list.
You can process in bulk of record of sObject by passing a list collection to DML operationg, that help to avoid DML state limit.(i.e. 150 DML )
List<Account> accList = new List<Account>(); // Define a new list Account a = new Account(Name='Acme'); // Create the account first Account b = new Account(Name='Acme2'); accList .add(a); // Add the account sObject accList .add(b) Account a2 = myList.get(0); // Retrieve the element at index 0 //Bulk insert the list insert accList;
Duplicate Insert or Upsert using List –
When list of sObject inserted or upserted successfully into database, it will generate the IDs for each record. Consequently a list of sObjects cannot be inserted or upserted if it contains the same sObject more than once, even if it has a null ID. This situation cause that tow IDs are required for the same structure in memory which is illegal.
Account a = new Account(Name='accTest'); List<Account> accList = new List<Account>(); accList.add(a); accList.add(a); insert accList;
Accessing Field name from SOQL query –
The SOQL qury returns a list of sObject, of which the first element(at index 0) is access through .
String nameChange = [SELECT Name FROM Account].Name.toLowerCase();