How to sort wrapper class list in Salesforce?

Comparable Interface is used to sort wrapper class list in Salesforce.

For more info, visit the below link

http://www.infallibletechie.com/2013/08/comparable-interface-in-salesforce.html

Sample Code:

Visualforce page:

<apex:page showHeader="false" controller="Sample" >
<apex:form >
    <apex:pageBlock >
        <apex:pageblockTable value="{!StudList}" var="S">
            <apex:column value="{!S.StudentName}"/>
            <apex:column value="{!S.StudentAge}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:form>     
</apex:page>

Apex Controller:

global class Sample {     
    public List<Student> StudList {get;set;}   

    public Sample() {
        StudList = new List<Student>();
        Student s1 = new Student('Ganesh', 12);
        StudList.add(s1);
        
        Student s2 = new Student('Arun', 82);
        StudList.add(s2);
        
        Student s3 = new Student('Vignesh', 32);
        StudList.add(s3);
        
        Student s4 = new Student('Younis', 55);
        StudList.add(s4);     
        
        Student s5 = new Student('Azhar', 42);
        StudList.add(s3);   
        
        StudList.sort();
    }
    
    //wrapper class for Comparable Interface
    
    global class Student implements Comparable {
        global String StudentName {get;set;}    
        global Integer StudentAge {get; set;}
        
        global Student(String Name, Integer Age) {
            StudentName = Name;
            StudentAge = Age;
        }
        
        global Integer compareTo(Object ObjToCompare) {
            return StudentName.CompareTo(((Student)ObjToCompare).StudentName);
        }
    }
}

Output:



Cheers!!!

9 comments:

  1. Very helpfull Post..

    ReplyDelete
  2. Actually this is not correct, if we use Custom sort then y do we need StudList.sort();

    ReplyDelete
    Replies
    1. This is correct. Here StudList is the list of comparable class instances.

      Cheers!!!

      Delete
  3. Awesome Post, It help me A lot. Thanks a lot...!!!!

    ReplyDelete
  4. It is displaying only one record in visual force page.

    ReplyDelete
  5. Hi , Thanks for the post .
    But this will not work if we have null values of the records in the list?

    ReplyDelete
    Replies
    1. Yes. You have to add the null check in compareTo(). Whether it should be added to the last or to the first.

      Delete
  6. Hi, I can able to create list of the wrapper class but i con't able to declare single record.

    Student temp = new Student ();
    like above

    ReplyDelete
    Replies
    1. You cannot use new Student () since it is using Parameterized Constructor. You can use new Student('Name', 89);//89 is the age.

      Delete