I have a list of AccountTeamMember records coming into a trigger handler class. From this list, I need to create a Map where each item is a key with the unique account ID based on the AccountTeamMember.AccountId field and then a value with a list of AccountTeamMember records that are for that account.
Example:
List of ATM records
- AtmID=100,AccountID=A001,UserId,U001
- AtmID=101,AccountID=A001,UserId,U002
- AtmID=102,AccountID=A002,UserId,U003
- AtmID=103,AccountID=A002,UserId,U004
- AtmID=104,AccountID=A003,UserId,U005
Map of Account IDs and List of ATM records
- AccountID=A001, <AtmID=100, AtmId=101>
- AccountID=A002, <AtmID=102, AtmId=103>
- AccountID=A003, <AtmID=104>
How would I could about creating this Map with Apex?
Best Answer
That's just a map of lists:
You'll want to remember this pattern, it's really common for many bulkification tasks.
Another common form you may find online reads like this:
Some people prefer this form, but it is relatively slow and inefficient, as I talk about in more detail in this answer.
In fact, it's so common, that I've used something like this as a generic method: