Sunday, June 19, 2011

Difference Between Trigger.New and Trigger.newMap in Apex




Trigger.new
 Returns a list of the new versions of the sObject records. Note that this sObject list is only available in    insert and update triggers, and the records can only be modified in before triggers.
Trigger.NewMap
A map of IDs to the new versions of the sObject records.
Note that this map is only available in before update, after insert, and after update triggers.
Note :   Trigger.newMap dont work for before insert while Trigger.New works fine for holding all Ids of records while inserting.
According to the docs, Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered. The docs specifically state you should not rely on the ordering of a map's elements.
What to use depends on what you're doing - if you have an ID of an object you need to do something with, using the map makes more sense as you can use newMap.get(). Otherwise you'd have to loop over all the elements in Trigger.new and look for a matching ID. Similarly, if you have multiple loops over each item the trigger is operating on, the list returned by Trigger.new may be the better bet.

3 comments: