Saturday, 6 June 2015

Using Comparable Interface to sort by Date

I have come across the requirement in which I have to sort the list of Apex Class based on Date.

If you want to add sorting support for Lists that contain non-primitive types, that is, lists of user-defined types. you must implement the Comparable interface with its compareTo method in your class.

To implement the Comparable interface, you must first declare a class with the implements keyword.
For sorting by date, we can use daysBetween(Date) which returns the number of days between that called the method and specified date.

Code Snippet of Apex Class:  
global class PaymentPlanList implements Comparable{
    public static List <PaymentPlanList> lstPaymentPlans {get;set;}
    public String Type {get;set;}
    public Decimal Amount {get;set;}
    public Date ToDate {get;set;}
    public Date FromDate {get;set;}
    public PaymentPlanList(PaymentPlan__c pp){
        Type = pp.Name;
        Amount = pp.Amount__c;
        ToDate = pp.To_Date__c;
        FromDate = pp.From_Date__c;
    public static List<PaymentPlanList> GetPayments(){
        if(lstPaymentPlans == null ){
            lstPaymentPlans = new List<PaymentPlanList>();
            for(PaymentPlan__c payment : [Select Name,Amount__c,From_Date__c,To_Date__c from PaymentPlan__c]){
                lstPaymentPlans.add(new PaymentPlanList(payment));
       return lstPaymentPlans;
    global Integer compareTo(Object compareTo) {
       //assuming if their is no date, it would be TODAY
       Date fromDatee = compareTo != null ? ((PaymentPlanList)compareTo).FromDate :;           
       return fromDatee.daysBetween(this.FromDate); // Sorting by Date
Sorting list of Apex Class and binded to VF page:
public class PaymentPlan{
    public List <PaymentPlanList> PaymentPlans {get;set;}
    public PaymentPlan(){
        PaymentPlans = PaymentPlanList.GetPayments(); // Calling Method of Outer Class for populating List of user-defined type
        PaymentPlans.sort(); // Adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.
Visuaforce Page:
<apex:page controller="PaymentPlan" >
    <apex:pageBlock >
        <apex:pageBlockTable value="{!PaymentPlans}" var="pp">
            <apex:column headerValue="Payment Type" value="{!pp.Type}" style="width:25%"/>
            <apex:column headerValue="Amount" value="{!pp.Amount}" style="width:25%"/>
            <apex:column headerValue="From Date" style="width:25%">
                <apex:outputText value="{0,date,MM/dd/yy}"> 
                    <apex:param value="{!pp.FromDate}"/> 
            <apex:column headerValue="To Date" style="width:25%">
                <apex:outputText value="{0,date,MM/dd/yy}"> 
                    <apex:param value="{!pp.ToDate}"/> 
If you notice the list is sorted by Date.
Feel free to post comments if you have any questions. Cheers !!!