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

Sorting a list


public with sharing class SampleTest {
 list<Contact>lstContact=new list<contact>();
 Map<string,Contact> mapContact=new Map<string,Contact>();
 list<WrapperSample>lstWrappersample=new list<WrapperSample>();
 public  list<WrapperSample> getEmployeeDetails(){
 lstContact=[select id,LastName,Email from contact];
 WrapperSample objwrapper;
 for(integer i=0;i<lstContact.size();i++){
    objwrapper= new WrapperSample();
 objwrapper.sName=lstContact[i].LastName ; 
for(string sInMsp : mapContact.keyset()){
Contact objCont = new Contact();
objCont= mapContact.get(sInMsp);
objwrapper= new WrapperSample();
objwrapper.sName=objCont.LastName ; 
system.debug('********lstWrappersample*******' + lstWrappersample.size());
return lstWrappersample; } public with sharing class WrapperSample{ public string sName {get;set;} public string sEmail {get;set;} } }
how can i sort the list name lstWrappersample?Can anyone help me in this regard..



So, just a thought before getting to your question.  Use spaces.  Blank lines, indentations, dare I say it, a comment or two.  etc.


If you're just trying to build a List of wrapper classes ordered by Last name, why not just use an Order By clause on your select statement, and then add the items to the list in the retrieved order.  (You seem to be building an intermediate Map for some reason)



public List<WrapperSample> getEmployeeDetails() {
    List<WrapperSample> lstWrapperSample = new List<WrapperSample>();
    for (Contact c: [select id, LastName, Email from contact order by LastName asc]) {
        lstWrapperSample.add(new lstWrapperSample(sName=c.LastName, sEmail=c.Email));
    return lstWrapperSample;




Another thought... many times if you're building a VF controller it's nice if you can build an Envelope class which seems to be what you're trying to do... I'm betting that you plan to add other things to your wrapper.


If that's the case, I'd suggest you consider that instead of storing the Email and Lastname in the wrapper class as new Strings, why not just store the whole Contact?  That way you can use <apex:inputField> tags on the variables instead of just treating them as strings.


So for example, one construct you sometimes see if you want to put a Checkbox next to a list of Object is something like:


public with sharing class Envelope {

public Boolean selected;

public Contact con;



List<Envelope> contacts {get; set;}



for (Contact c: [select..... order by ....]) contacts.add(new Envelope(selected=False, con=c));


(Or, I may be totally off base with what you're trying to do.)


Best, Steve.