function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Muruganand_SforceMuruganand_Sforce 

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

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

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.

 

Map<String, List<Account>> nameMap = new Map<String, List<Account>>();
for (Account a: existingListAccount) 
{
   List<Account> candList=nameMap.get(a.name);
   if (null==candList)
   {
      candList=new List<Account>();
      nameMap.put(a.name, candList);
   }
   candList.add(a);
}
existingListAccount.clear();
for (String s: nameMap.keySet().sort()) 
{ existingListAccount.addAll(nameMap.get(s)); }

 

All Answers

SteveBowerSteveBower

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.

bob_buzzardbob_buzzard

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.

 

Map<String, List<Account>> nameMap = new Map<String, List<Account>>();
for (Account a: existingListAccount) 
{
   List<Account> candList=nameMap.get(a.name);
   if (null==candList)
   {
      candList=new List<Account>();
      nameMap.put(a.name, candList);
   }
   candList.add(a);
}
existingListAccount.clear();
for (String s: nameMap.keySet().sort()) 
{ existingListAccount.addAll(nameMap.get(s)); }

 

This was selected as the best answer
Muruganand_SforceMuruganand_Sforce

Thanks a lot to both of you Guys!!!!

Muruganand_SforceMuruganand_Sforce

Hi,

 

I am getting the following Error

 

expecting right curly bracket,found 'for'. at Line no 2 in the code.

 

Muruganand_Sforce

bob_buzzardbob_buzzard

You'll need to put this inside its own method.

Tom MapleTom Maple

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.

 



bob_buzzardbob_buzzard

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.

Adil_SFDCAdil_SFDC

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

 public void createDocuments(JSONParser parser)
    {
        documentList = new List<Document>();
        Document doc = new Document();
        Integer position = 0;
        while (parser.nextToken() != null) 
        {
       if (parser.getCurrentToken() == JSONToken.START_OBJECT ||parser.getCurrentToken() ==JSONToken.END_OBJECT ) 
           {   
                if(doc.title != null)// && doc.url != null && doc.rating != null && doc.filetype != null && doc.id != null && doc.description != null)
                {
                    doc.position = position;
                    position++;
                    documentList.add(doc);
                    
                    doc = new Document();
                } 
                    
            }
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) 
            {
                if(parser.getText() == 'title')
                {
                    parser.nextToken();
                    doc.title = parser.getText();
                }
                if(parser.getText() == 'id')
                {
                    parser.nextToken();
                   doc.id = parser.getText();
                   system.debug('DDDDD'+doc.id);
                   String sortid = doc.id.sort();
                    docIdsList.add(doc.id);
                    
                }
   

 Thanks

Adil

 

bob_buzzardbob_buzzard

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.

Adil_SFDCAdil_SFDC

Thanks for reply Bob

 

Here is what i Did 

if(parser.getText() == 'id')
                {
                    parser.nextToken();
                   doc.id = parser.getText();
                  
                   
                    docIdsList.add(doc.id);
                    docIdsList.sort();
                    //sid.sort();
                     system.debug('DDDDD'+docIdsList);
                }

 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

DDDDD(5252, 5253, 5254, 5258, 5259, 5262, 5267, 5410, 6138, 6141, ...)
bob_buzzardbob_buzzard

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