1

I have code below

public class LearnAboutMap {
     public LearnAboutMap () {
          Map<String, String> m = new Map<String, String>();
          m.put('Type', '1');
          m.put('Contact', '1');
          m.put('Additional', '1');
          m.put('Supper', '1');
          m.put('Body', '1');
          System.debug(m);

          //Output: {Additional=1, Body=1, Contact=1, Supper=1, Type=1}
          //Expected: {Type=1, Contact=1, Additional=1, Supper=1, Body=1}
     }

}

Why Map in Apex is auto sort key ?

  • Out of curiosity, why does it matter? – PartOfTheOhana May 22 at 4:51
  • @Ohana I want to show map in visualforce page position extractly – Davis Clack May 22 at 4:55
2

You're looking at the internal stringified representation of the map that is made available to you for debug purposes. The Map class does not specify the order of keys, there's no "auto sort". Deterministic ordering is only guaranteed on map's elements via values() method.

1

Not sure if this answers your question, but here's what the docs say on how they are implemented:

Apex uses a hash structure for all maps, and the The iteration order of map elements is deterministic. You can rely on the order being the same in each subsequent execution of the same code. However, SF recommends to always access map elements by key.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps.htm

  • I want to put any key and value exactly position but it always sorted by key – Davis Clack May 22 at 4:54
  • If that’s the result you want , then don’t use a map. Use a list of something.... given the example above, use a list of maps, where each list element has a map of 1 key value pair. – PartOfTheOhana May 22 at 12:32
1

Since you want Map keys to be iterated in the order you placed in the Map. So convert the Map.keySet() to List and it will be sorted.

Map<String, String> m = new Map<String, String>();
m.put('Type', '1');
m.put('Contact', '1');
m.put('Additional', '1');
m.put('Supper', '1');
m.put('Body', '1');
System.debug(new List<String>(m.keySet()));

12:04:32:003 USER_DEBUG [7]|DEBUG|(Type, Contact, Additional, Supper, Body)

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.