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
AlanPerkinsAlanPerkins 

APEX Code: Working with Maps inside a list

    I have a list defined as List<Map<ID, MyObject__c>> and I am populating multiple maps of these objects into the list as separate entries in the list.
That all appears to work OK.

I am trying to access the records inside the maps inside the list and am running into problems:

It doesn't matter which way I seem to write the inner for loop, I get one error or another on the inner loop -

for(Integer i = counter; i == 0; i--) {
    for(MyObject__c person:peopleList[i]) {
       //do stuff with person
    }
}

or

for(Integer i = counter; i == 0; i--) {
    Map<ID, MyObject__c> p = (Map<ID, PNP_Person__c>)peopleList[i];
    for(MyObject__c person:p) {
       //do stuff with person
    }
}


How do I reference the internal map in the list here?

The error message given here is "Initial term of field expression must be a concrete SObject: LIST:MAP:Id,SOBJECT:MyObject__c "


Thanks in advance for any assistance!
Jim_morrisonJim_morrison
Syntax error isn't it ?  The <variable> below in your case is not an of the same sObject type i.e. "Map"  
Code:
 
for (<variable> : <list_or_set>) {
<code_block>
}
where <variable> must be of the same primitive or
sObject type as <list_or_set>.

Did u try something like this already?

Code:
 
for(Map<ID,my_object> myMap: <yourList>) {
//work on each Map
<code_block>
}

 


 

ASBPASBP
Hi Jim,

Thanks for your response. Unfortunately it hasn't helped: firstly it doesn't seem to work and secondly I need to traverse the list backwards, hence the negative counter. How can I  refer to the maps inside the list by index?
wintamutewintamute
Hi,

as the inner loop is supposed to work on a Map, you have to use the right methods to access the contained data

for(Integer i = counter; i == 0; i--) {
    Map<ID, MyObject__c> p = (Map<ID, PNP_Person__c>)peopleList[i];
    for(MyObject__c person:p) {   <-- p is a map here
       //do stuff with person
    }
}

This doesn't work since p is a Map, so the MyObject__c cannot be accessed directly. Try the values() method instead, like this:

for(Integer i = counter; i == 0; i--) {
    Map<ID, MyObject__c> p = (Map<ID, PNP_Person__c>)peopleList[i];
    for(MyObject__c person: p.values()) {
       //do stuff with person
    }
}

See also the Apex language reference, page 149 on Map methods.

Cheers,
Andreas