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 ?

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

3 Answers 3

3

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)

2

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

2
  • I want to put any key and value exactly position but it always sorted by key May 22, 2019 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. May 22, 2019 at 12:32
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.

2

You must log in to answer this question.

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