when i query and put in list and put key as a account and values as a contact its working, but when i declared its showing error "Invalid initializer type List found for Map>: expected a Map with the same key and value types, or a valid SObject List"

    Map<Id,List<contact>> AccConMap = new Map<Id,List<contact>>([SELECt id,
                                         (Select id, firstname From
                                            Contacts) FROM Account LIMIT 10]);

   System.debug('Account Key-->'+AccConMap.KeySet()+'Contact Values'+AccConMap.Values());

2 Answers 2


If you want to create a Map<ID, List<Contact>>, you will need to do something like this. It will use your AccountID from the contact as the key and will add contacts as the values.

Map<ID, List<Contact>> accountIDToContactMap = new Map<ID, List<Contact>>();

Map<ID, Contact> contactMap = new Map<ID, Contact>([Select ID, Firstname, AccountID FROM Contact]);

for(ID contactID : contactMap.keySet())
        accountIDToContactMap.put(contactMap.get(contactID).AccountID, new List<Contact>{contactMap.get(contactID)});


The return type of your SOQL query is List<Account>, which can be passed to a Map constructor to generate a Map<Id, Account>. If you want to extract the contact lists, you can iterate over the list in Apex to populate a Map<Id, List<Contact>> with each Account's Contacts property (whose type is List<Contact>), but the default constructor won't do that for you.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .