+ Start a Discussion

Looping over Nested Maps

Man, once you start programming for Salesforce you really realize what a pain it can be moving from a weak-typed language (cough PHP) to a strongly typed language like Apex. Trying to replicate the familiar behavior of nested arrays in Apex has proven to be quite difficult.


So, I have a nested map defined:



Map<String, Map<String, List<Decimal>>> return_data = new Map<String, Map<String, List<Decimal>>>();


 Further down in my code, I'm attempting to loop this map with a for loop:


for(Map<String, Map<String, List<Decimal>>> c_data : return_data) { ... }


However, the server complains:



Save error: Loop must iterate over a collection type: MAP:String,MAP:String,LIST:Decimal 


What am I missing here?



Lets simplify it by replacing the nested map by an object


Map<String, OBJ__c> myMap = new ....

so to iterate through this you can either


for (String myStr : myMap.keySet()) { OBJ__c myObj = myMap.get(myStr); ... } or for (OBJ__c myObj : myMap.values()) { ... }


now imagine your nested map in place of the object


for (String myStr : myMap.keySet()) { Map<String,List<Decimal>> myNestedMap = myMap.get(myStr); ... }




for (Map<String,List<Decimal>> myNestedMap : myMap.values()) { ... }




You can then nest some for loops so you can iterate over the nested maps as well.