You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Comparable Interface in Salesforce


Comparable Interface

Salesforce provides an Interface called Comparable to implement a custom sort order for SObjects or wrapper Class in lists. The Comparable interface adds sorting support for Lists that contain non-primitive types. Whenever we want to sort a column in the wrapper list, then we have to implement the Comparable interface, and we should implement the “compareTo ()” method. In this method, we need to implement the logic for comparison.

In the below example, a Wrapper class (OpportunityWrapper) list is sorted by using Amount field, and it is sorted in the ascending order–basically a wrapper class can contain combination of different types of fields. So, we need to use the Comparable interface for sorting the wrapper list.

Implementing the Interface:

Public class OpportunityWrapper implements Comparable {

}

CompareTo () method:

Public Integer compareTo (Object compareTo) {

}

The implementation of this compareTo () should return the following values:

Return 0 if this instance and “compareTo” Object are equal

Return > 0 if this instance is greater than “compareTo” Object

Return < 0 if this instance is less than “compareTo” Object

Example:

Visualforce Page:

<apex:page controller="OpportunityListController">
<apex:pageBlock> 
<apex:pageBlockTable value="{!OpportunityList}" var="opp">
<apex:column value="{!opp.oppName}" headerValue="Opportunity Name"/>
<apex:column value="{!opp.oppAmount}" headerValue="Opportunity Amount"/>
<apex:column value="{!opp.oppStageName}" headerValue="Opportunity Stage"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

Controller:

Public class OpportunityListController {
Public List<opportunityWrapper> getOpportunityList () {
List<opportunityWrapper> opportunityWrapList = new List<opportunityWrapper> ();
For (opportunity opp: [select name,stageName,amount from opportunity]){
opportunityWrapList.add (new OpportunityWrapper(opp.name,opp.stageName,opp.amount));
}
If (opportunityWrapList! = null && opportunityWrapList.size () > 0) {
opportunityWrapList.sort ();
}
Return opportunityWrapList;
}

Wrapper Class:

Public class OpportunityWrapper implements comparable {
Public String oppName {get;set;}
Public String oppStageName {get;set;}
Public Decimal oppAmount {get;set;}
Public opportunityWrapper (String oppName,String oppStageName,decimal oppAmount){
This.oppName = oppName;
This.oppStageName = oppStageName;
This.oppAmount =oppAmount;
}
Public Integer compareTo (Object compareTo) {
opportunityWrapper oppW = (opportunityWrapper)compareTo;
Integer returnValue = 0;
If (oppAmount > oppW.oppAmount) {
returnValue = 1;
} else if (oppAmount < oppW.oppAmount) {
returnValue = -1;
}
Return returnValue; 
}
}
}

Result:

Comparable interface

Reference:

Comparable Interface in Salesforce