You need to sign in to do that
Don't have an account?

Sort a List with List<Account> type?
Hi,
I want to list of Accounts based on Account Name. Obviously It is not possible with sort() function.Any short cut?
Inputs are welcome.
Regards,
Muruganand_Sforce
One gotcha with the solution above is that if you have two accounts with the same name, you'll overwrite the first with the second in the map and it won't appear in the final sorted list. This can be avoided by storing a list of accounts against the name rather than a single instance. E.g.
All Answers
Well, the easiest way is to get your list from the database in a sorted order to begin with using "Order By".
However, if you have "List<Account> existingListAccount", and you want to traverse it in an order sorted by Name you can do:
Map<String, Account> nameMap = new Map<String, Account>();
for (Account a: existingListAccount) nameMap.put(a.name, a);
existingListAccount.clear()
for (String s: nameMap.keySet().sort()) {
existingListAccount.add(nameMap.get(s));
}
Best, Steve.
One gotcha with the solution above is that if you have two accounts with the same name, you'll overwrite the first with the second in the map and it won't appear in the final sorted list. This can be avoided by storing a list of accounts against the name rather than a single instance. E.g.
Thanks a lot to both of you Guys!!!!
Hi,
I am getting the following Error
expecting right curly bracket,found 'for'. at Line no 2 in the code.
Muruganand_Sforce
You'll need to put this inside its own method.
In Force.com IDE, entering this generates this error:
Method does not exist or incorrect signature: [SET<String>].sort()
According to the documentation, there is no sort() function on the Set type.
That makes perfect sense, as set is unordered.
I'd imagine the keyset needs to be put into a list and that is what gets sorted.
Hi Bob
I need a little help here. I am displaying documents from a website on VF Page. The order it is displayed is ascending.
I want to display it in descending order. I am using sort() method.
I get following error
Method does not exist or incorrect signature: [String].sort()
Here is my code
Thanks
Adil
doc.id is a string, but the sort method works on lists. If you want the ids in order, you'll need to put them in a list and sort that.
Thanks for reply Bob
Here is what i Did
When i check debug log this is what i see. I want this in descending order. How do i do that, and how do idisplay on VF Page
Two ways I can think of:
(1) Iterate the list in reverse order and add those elements to a new list
(2) Implement a custom sort order as detailed in:
http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_lists.htm#list_sobject_sorting