I have a list accountList which contains corresponding contacts aswell. Now I am trying to make a map from that list with key as single account and corresponding associated contacts as value.

public class ListToMapConversion {
   public list<Account> accountList =new list<account>();
    public map<Account,contact> accmap=new map<Account,contact>();
    public void convert(){
        accountlist=[select id,name,(select lastName,phone,email from contacts) from account];

        for(Account a:accountlist){



  • So what's your problem exactly? Generally, using SObjects as keys in a Map is not a good practice due to performance issues and keys must be immutable. Use Account Id instead
    – Eduard
    Aug 14 '18 at 9:50
  • getting an error saying that list has no rows. But when I execute the query in the query editor am getting records
    – user59277
    Aug 14 '18 at 9:52
  • 2
    That error couldn't occur here. Your problem is elsewhere.
    – sfdcfox
    Aug 14 '18 at 10:22
  • not getting any records to display after its executed. no errors as well
    – user59277
    Aug 15 '18 at 9:09

Since a.contacts returns the List<Contact> so, variable declaration needs to be changed as follows:

public map<Account,List<contact>> accmap=new map<Account,List<contact>>();

And rest of the code will work fine.

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.