Use Left Shift Operator To Append to Lists
To append elements to an existing list, use the left shift operator (<<) or call the list's add() function for best performance.
For example, the following code processes a collection of products and adds the value of
the Id
field from a subset of the products encountered to a new
list:
list productIdsToProcess = []
for (prod in products) {
if (prod.Status == 'RETURNED') {
// Append the current product id to the list
// Same as calling productIdsToProcess.add(prod.Id)
productIdsToProcess << prod.Id
}
}
This technique is better than using the plus or plus-equals operator to do the same job because both of those create a new list each time.