+ Start a Discussion

Iterating through a Map, Value Order

I have a trigger where I create a Map of SObjects using a query that includes an ORDER BY statement.  My hope was that the values in the map would then be in the same order as the results of the query, but when I iterate through them, that's not the case. Any way to set the order of the values in a map, or do I need to accomplish this differently?

My code, for reference:
//Get map of statuses for participants
 Map<Id, Status_Milestone__c> statMap = new Map<Id, Status_Milestone__c>(
   [select Id, Participant__c, Category__c, Sub_Category__c, Status_Milestone__c, Effective_Date__c
   from Status_Milestone__c
   where Participant__c IN :partIds and 
   (Sub_Category__c = 'Reinstated - Redevelopment' or Sub_Category__c = 'Reinstated')
   ORDER BY Effective_Date__c ASC]);

//Since this is sorted by date, the last reinstatement status hit should be the most recent
   for (Id statId:statMap.keySet()){
    cat = statMap.get(statId).Category__c;
    part = statMap.get(statId).Participant__c; 
    if (part == Trigger.new[i].Participant__c && cat == 'Active, Post-Placement Services') {
     booPost = true;
    } else {
     //reset to false just in case there are multiple reinstatements
     booPost = false;


Ron HessRon Hess
The doc has this hint:
 Apex uses a hash structure for all maps.

So, based on your observation and this note in the doc, I'd say that a Map is not an ordered set, rather is a hashed collection designed for access by key.

I believe a List will preserve the order of records in the SOQL.
You could create list, then walk thru the list and create a map, allowing for access of your data by order or key.

Ron, I found a different way to accomplish what I was trying to do, but this useful to know. Thanks!