function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BroncoBoyBroncoBoy 

Need Help Generating a Map Of Lists

We have Account records with a field of FS_ID__c (text).  Several accounts may have the same FS_ID__c.  I would like to generate a map of the reverse:  a map of lists where we show which account ID's  are associated to each particular FS_ID__c.  I want the map to include all FS_ID__c's.  Is that possible?  If so, how can I poplulate the map?  My intent is to use MyMap.get() method to give me the accounts for FS_ID__c '1234'. The purpose:  to avoid running a query each time I want to know the accounts associated to each FS_ID__c.  Thanks in advance for your help - alternative suggestions/approaches are welcome as well.

Example of desired effect:
public map <String, list <String>> MyMap = new map <String, list <String>>
{
   'FSID1234' => new list<String> {'a0yW0000000zC177', 'a0yW0000000zC178', 'a0yW0000000zC179'},
   'FSID5678' => new list<String> {'a0yW0000000zC187', 'a0yW0000000zC188', 'a0yW0000000zC189'},,
   'FSID5678' => new list<String> {'a0yW0000000zC197', 'a0yW0000000zC198', 'a0yW0000000zC199'},
};

Referernce:
http://www.davehelgerson.com/?p=379
Best Answer chosen by BroncoBoy
BalajiRanganathanBalajiRanganathan
Try the code template below.

Map <String, List <String>> myMap = new Map <String, List <String>>();

for (Account account :  [Select id, FS_ID__c from Account]) {
   List<String> accounts = myMap.get(account.FS_ID__c );
   if (accounts == null) {
     accounts = new List<String>();
     myMap.put(account.FS_ID__c, accounts);
   }
  accounts.add(account.id);
}

All Answers

BalajiRanganathanBalajiRanganathan
Try the code template below.

Map <String, List <String>> myMap = new Map <String, List <String>>();

for (Account account :  [Select id, FS_ID__c from Account]) {
   List<String> accounts = myMap.get(account.FS_ID__c );
   if (accounts == null) {
     accounts = new List<String>();
     myMap.put(account.FS_ID__c, accounts);
   }
  accounts.add(account.id);
}
This was selected as the best answer
BroncoBoyBroncoBoy
That's it, thank you!