2

My understanding is that map keys are auto ordered and case sensitive. When I printed the map or map.ketSet(), it is as expected. However when I tried iterating over the keySet or try to convert it to list it gets shuffled in a random order.

Snippet:

map<string, string> test = new map<string, string>();
test.put('xyz','XYz');
test.put('x','x');
test.put('abc','Abc');

system.debug('map**'+test); // |DEBUG|map**{abc=Abc, x=x, xyz=XYz}
system.debug('map keys**'+test.keySet()); // DEBUG|map keys**{abc, x, xyz}

for(String s :test.keySet()){
    system.debug(s + '----map---'+ test.get(s));
    //|DEBUG|xyz----map---XYz
    //|DEBUG|x----map---x
    //|DEBUG|abc----map---Abc
} 

Looks like even converted list is not preserving the order:

list<string> testLst = new list<string>(test.keySet());
system.debug('keyset List**'+testLst); //|DEBUG|keyset List**(xyz, x, abc)

So far, I got a native workaround, using list method sort().

Work around:

list<string> testLst = new list<string>(test.keySet());
testLst.sort();
system.debug('keyset List**'+testLst); //|DEBUG|map List**(abc, x, xyz)

-

Curious to know more on this behavior, any inputs is appreciated.

2
  • 1
    Despite the critical update, you still should not rely on the order. If you need an explicit order (e.g. sorted ascending), use a list and sort it.
    – sfdcfox
    Commented Aug 2, 2017 at 15:15
  • @sfdcfox, Agreed. That's something I understood form the answer discussion. Thanks much for the confirming the same. Commented Aug 3, 2017 at 13:54

1 Answer 1

3

It seems like you are using old API version 34.0 or less because Salesforce pushed this critital update in Summer'15 release

"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."

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
1
  • 1
    @Pradeepkumar'2552866 Sets and Maps are unordered collections (and a Map's keyset is, like the name suggests, a Set), The 'order' that you're seeing is an artifact of using system.debug() to display the set in your debug log.
    – Derek F
    Commented Aug 2, 2017 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .