0

In the code below, I get compiler error on Loop must iterate over collection: Account

Can anyone help me about this issues.

 list<Account> acc =[Select Id, (Select Id, Name from ChildAccounts) from Account];
        Map<Id, Account> accMap = new Map<Id, Account>();
        for(account a: acc){
            for(account b: a.ChildAccounts){
                accMap.put(a.Id, b);
            }
        }
        
        Account acclst = accMap.get('00O28000004oRjdEAE');
        
        for(Account a: acclst){
            
        }

1 Answer 1

3

The compiler is expecting a list of accounts for the below for loop, but it is account.

Account acclst = accMap.get('00O28000004oRjdEAE');
for(Account a: acclst){
        
}

So the map should be Map<Id, List<Account>>, use the below code to put the values into the map.

Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
for(account a: acc){
    accMap.put(a.Id, a.ChildAccounts);
}

Finally, the for loop will be like below.

for(Account a: accMap.get('00O28000004oRjdEAE')){ // never use hard coded ids
        
}

You must log in to answer this question.

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