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.