How to sort wrapper class list in Salesforce?

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

https://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!!!

Leave a Reply