0

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());
0

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())
{
    if(accountIDToContactMap.containsKey(contactMap.get(contactID).AccountID))
    {
        accountIDToContactMap.get(contactMap.get(contactID).AccountID).add(contactMap.get(contactID));
    }
    else
    {
        accountIDToContactMap.put(contactMap.get(contactID).AccountID, new List<Contact>{contactMap.get(contactID)});
    }
}

System.debug(accountIDToContactMap);
| improve this answer | |
1

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.