When we execute a code

Map<String, String> tm = new Map<String, String>{
System.debug(LoggingLevel.ERROR, '@@@ v: ' + String.join( new List<String>(tm.keySet()), ',') );
System.debug(LoggingLevel.ERROR, '@@@ v: ' + tm.keySet() );

the first debug displays correct order

@@@ v: Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday

while the second debug displays incorrect order

@@@ v: {Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday}

This means that even despite a keyset is a set and unordered collection, Salesforce remembers the correct order and when you convert this set into list, Salesforce provides correct order.

Is such behavior documented anywhere?


Looks like since Summer'15 iteration order for sets and maps is now predictable and these release notes might explain such behavior.

The order of elements in unordered collections (Map and Set) is now the same each time your code is run. Previously, the order of elements in unordered collections was arbitrary, and you couldn’t rely on the order of elements in maps and sets. Ideally, you don’t want your code to depend on the order of elements in unordered collections. If you have such code, it could sometimes fail before this change. This change makes your code more robust because the iteration order in maps and sets is always the same.

This example illustrates how the iteration order is deterministic in a map. A map is created with two elements. Next, the for loop iterates over the map elements and writes the key and value of each element to the debug log. Each time you execute this snippet, the iteration order of the elements in the for loop is the same.

Map<String, String> currencyMap = new Map<String, String>();
currencyMap.put('France','Euro'); currencyMap.put('Japan', 'Yen');
// Iterate through the map elements. 
for (String mapKey : currencyMap.keySet()) {
            System.debug('Key: ' + mapKey +
                ', Value: ' + currencyMap.get(mapKey)); }

        // The output is: Key: France, Value: Euro Key: Japan, Value: Yen
  • The example on the question side might be a little risky because the keys have an inherent order (the days of the week) that Salesforce is not guaranteeing to return, as I read this doc. It's guaranteeing some deterministic order, not creation order, even though that appears to be the current strategy. – David Reed Apr 26 '18 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.