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!!!

5 comments:

  1. 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
  2. Awesome Post, It help me A lot. Thanks a lot...!!!!

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

    ReplyDelete