+ Start a Discussion

Map<ID, List<Contacts>> what is the rationale of using list in maps?

I was gong through the Apex code and found out a code line;

Map<ID, List<Contacts>> mapCntList1 = new Map<ID, List<Contacts>>();

I was wondering this statement could have been written like this also;
Map<ID, Contacts> mapCntList2 = new Map<ID, Contacts>();
If the list declaration in "mapCntList1" is correct, can anyone tell when this should be used and when "mapCntList2" should be used?

Suraj GharatSuraj Gharat
Any of the above statements can be used depending on your requirement/logic, provided both the parameters to the MAP must be accessble types.

In case of mapCntList1, List<Contacts> (I suppose, this is List<Contact> not List<Contacts>), must be a valid data type, and this would create a map that has a list of contacts for each given id.
For second case, if you wanna use "Map<ID, Contacts>" ( Again, I suppose, this is Contact not Contacts) , you can use it that way, but notice, this will create a map that has a contact (not list) for each given id.

You may refer below link for more details.

NagaNaga (Salesforce Developers) 
Hi DD,

Please check the link below 


Best Regards
Naga kiran
Ankit BobdeAnkit Bobde
1) As Suraj said it is Contact not Contacts and if it is Contacts it should be like Contacts__c because every custom objects must end with __c.

2)  a) mapCntList1 - Refers to a map in which every key(ID) is associated with lists if contact . 1 key --> list of contact(contact Records say-c1,c2,c3,c4)
b) mapCntList2  - Refers to a map in which every key(ID) is associated with a single instance of contact or you can say a single contact record .
1key --> Single instance if contact (contact Record say - Con1)

Now both of them are different
1) If you come across a scenario where your key will be associated with list of contacts use mapCntList1 . for e.g. 1 ID(Say Account ID)  have multiple Contact
2) In rather case use mapCntList2.
Thanks all of you!!