How to use Comparable Interface in Salesforce

The Comparable interface use for sorting : Lists that contain non-primitive data types, that is, Lists of user-defined types.
In Apex you need to implement the Comparable interface with its compareTo method in your class.

When a class implements the Comparable interface it has to implement a method called compareTo(). 
In this method the code has to be verified if two objects match or if one is larger than the other.

Class Code

global class  CamprableInterfaceExampleController {


    public List<WrapperClass> WrapperList {get;set;}   

    public CamprableInterfaceExampleController () {
        WrapperList = new List<WrapperClass>();
        WrapperClass s1 = new WrapperClass('Sumit', 22);
        WrapperList.add(s1);
        
        WrapperClass s2 = new WrapperClass ('Amit', 15);
        WrapperList.add(s2);
        
        WrapperClass s3 = new WrapperClass ('Rahul', 55);
        WrapperList.add(s3);
        
        WrapperClass s4 = new WrapperClass ('Naveen', 35);
        WrapperList.add(s4);     
        
        WrapperClass s5 = new WrapperClass ('Vijay', 25);
        WrapperList.add(s5);   
        
        WrapperList.sort();
    }
    
    //wrapper class for Comparable Interface
   
    global class WrapperClass implements Comparable  {
        global String StudentName {get;set;}    
        global Integer StudentAge {get; set;}
        
        global WrapperClass(String Name, Integer Age) {
            StudentName = Name;
            StudentAge = Age;
        }
        
        global Integer compareTo(Object ObjToCompare) {
            return StudentName.CompareTo(((WrapperClass)ObjToCompare).StudentName);
          
        }
    }
}

PageCode


<apex:page showHeader="false" controller="CamprableInterfaceExampleController" >

  <apex:form >
    <apex:pageBlock title="Camprable Interface Example">
        <apex:pageblockTable value="{!WrapperList}" var="S">
            <apex:column value="{!S.StudentName}" headerValue="Name"/>
            <apex:column value="{!S.StudentAge}" headerValue="Age"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:form>     
  
</apex:page>


Screen Shot



Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page