function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
VisithraVisithra 

Help me with code, created aggregateresult into map to count number of records with rating grouped., I Got stucked while traversing Loop

Map<ID, AggregateResult> accountMap=new Map<ID, AggregateResult>([Select 
                                                                 count(ID) ratingCount, Rating
                                                                 From Account
                                                                 Group by Rating
                                                                ]);
for(AggregateResult accRecord:accountMap)
{
    system.debug('ratingCount');
    system.debug(accRecord.get('Rating'));
}

Getting error as:: Line: 6, Column: 1
Loop must iterate over collection: Map<Id,AggregateResult>
Arun Kumar 1141Arun Kumar 1141

Hi visi,
You have to iterate on Map values i.e.,


Map<ID, AggregateResult> accountMap=new Map<ID, AggregateResult>([Select 
                                                                 count(ID) ratingCount, Rating
                                                                 From Account
                                                                 Group by Rating
                                                                ]);
for(AggregateResult accRecord:accountMap.values())
{
    system.debug('ratingCount');
    system.debug(accRecord.get('Rating'));
}

Please mark this as the best answer if this helps.

VisithraVisithra
Hi, Thanks for replying.., but am getting error as System.ListException: Row with null Id at index: 0
Arun Kumar 1141Arun Kumar 1141

To avoid this error Please Use a list instead of a map.

This will give you the count and the rating.

List< AggregateResult> accountMap=new List< AggregateResult> ([Select 
                                                                 count(ID) ratingCount, Rating
                                                                 From Account
                                                                 Group by Rating
                                                                ]);
for(AggregateResult accRecord:accountMap)
{
    system.debug('ratingCount'+accRecord.get('ratingCount'));
    system.debug(accRecord.get('Rating'));
}
 

SwethaSwetha (Salesforce Developers) 
Adding to Arun's comment, regarding the System.ListException: Row with null Id at index: 0 error, the below similar posts can help

https://salesforce.stackexchange.com/questions/284260/fatal-errorsystem-listexception-row-with-null-id-at-index-0
https://salesforce.stackexchange.com/questions/327000/assign-map-keys-and-values-to-account
https://salesforce.stackexchange.com/questions/160220/compile-error-loop-must-iterate-over-a-collection-type-mapid-listevent