You need to sign in to do that
Don't have an account?
Tux
Map not being showed in sorted order inside repeat tag, despite being sorted in Controller.
Hi,
I am displaying the contents of a Map on a Visualforce page. This map is sorted by first putting the contents in a list, and then putting the list contents in a Map, as answered in another thread on this board. Here are my code snippets:
<apex:pageBlockSection columns="2" collapsible="true" title="{!title}" rendered="{!IF(condition >0,true,false)}" > <apex:repeat value="{!MapSortedInCode}" var="count"> <apex:pageBlockSectionItem>{!count}</apex:pageBlockSectionItem> <apex:pageBlockSectionItem>{!MapSortedInCode[count]}</apex:pageBlockSectionItem> </apex:repeat> </apex:pageBlockSection>
public Map<String, Integer> sortMap(Map <String, Integer> someMap){ Map<String, Integer> newMap = new Map<String, Integer>(); List<String> aList = new List<String>(); aList.addAll(someMap.keySet()); aList.sort(); System.debug('aList::'+aList); for(String a: aList){ Integer value = someMap.get(a); newMap.put(a, value); } return newMap; }
These are the outputs of the Debug Log:
|DEBUG|Before sorting Map: {Armenia=1, Belgium=1}
|DEBUG|aList::(Armenia, Belgium)
|DEBUG|After sorting Map: {Armenia=1, Belgium=1}
However, on the visualforce page, the Map is not displayed in a sorted manner. Its neither ascending, nor descending, or alphabetical, or sorted by value. Can anyone tell me what the issue is?
Thanks a lot.
I used a list, and it was the best way to solve the problem.
CountryList (contains the keys) is used to lookup the value inside CountryCountMap.
Thanks for helping out :)
All Answers
A Map cannot be sorted. When you iterate over it you get it in whatever order the map happens to be stored in; this has nothing to do with the order thay you added entries.
Use a List if you need a particular order.
In your case, iterate over the sorted list of keys and use that to select from the map.
The debug logs shows the values of the Map in the correct order of insertion. I am satisfied with the order, as is it correct. However, this order is not preserved when displaying in the VF page.
From the Apex Developer's Guide:
--- snip ---
Do not rely on the order in which map results are returned. The order of objects returned by maps may change without warning. Always access map elements by key.
--- snip ---
This is expected behaviour. As aballard has recommended above, use lists if you need ordering.
I used a list, and it was the best way to solve the problem.
CountryList (contains the keys) is used to lookup the value inside CountryCountMap.
Thanks for helping out :)