To add to @SFDCfox's answer, if the data is in the trigger.new or trigger.newmap or trigger.oldmap, there's no need to query for it. Obviously, it counts against the number of SOQL queries allocated to your org over a 24 hr period. It also slows down your trigger and makes it less efficient.
As you mention lists, maps and sets are generally more efficient than lists. They remove duplicate information and prevent the dreaded "list exception" than can occur when a list contains more than one instance of the same object ID. To be safe, that's when you'll want to test to make certain the list you're adding to doesn't already contain the same object ID. If you put
a second instance of the key
with an associated value
to a Map that contains the same ID, the previous value
for that key
is overwritten, so no problem and no exception occurs (hopefully you have the desired value, with an ID as the key, that's highly likely; but much less so with a string).
@sfdcfox has clearly explained an excellent method for obtaining nested information from a map.
If you do find yourself searching a database, a map construction is also a valid one to use when constructing your search query
, especially if multiple related objects are being queried. There's a simple method for retrieving the data as well using nested for loops that are to me, always seem simpler than above. As that doesn't apply to your particular situation, I won't explain it here since it doesn't apply to your particular use case. It does however result in retrieving all your data in lists
.
You'll find an example of a method to use as described in my answer to Salesforce: Apex Update Object And All Child Object Records Associated to Parent Object.