How to sort Wrapper list?

I have a wrapper class which contains a list of sobjects, i want to have th sorting on the fields of these objects in the wrapper list:
The apex code is as follows:

Class jobsWrapper {
    public JobSuite__Job__c job { get; set; }
    public JobSuite__Job_Task__c jobTasks { get; set; }

    public JobsWrapper(JobSuite__Job__c objjobs, JobSuite__Job_Task__c objjobTasks) {
        // if(jobTasks== NULL){jobTasks = new List<Job_Task__c>();}
        job = objjobs;
        jobTasks = objjobTasks; 
    }

    public JobsWrapper() {
        if(jobTasks== NULL) {
            jobTasks = new JobSuite__Job_Task__c();
        }

        if(job == NULL) {
            job = new JobSuite__Job__c();
        }        
    }
}

I want to allow sorting the wrapper list by the fields in the job – like client, jobname, jobnumber etc and fields from the task object as taskname, reviseddue dateetc.

How can I do this?
Please help, thanks in advance.

Answer

Apex provides a sort method on the List class for sorting. For objects such as this however, you must implement the Comparable interface. Note the Salesforce doc samples indicate you need to make your class ‘global’ scope, this is no longer true.

public class jobsWrapper implements Comparable
{
    public Integer compareTo(Object compareTo) 
    {
        jobsWrapper jobsWrapper = (jobsWrapper) compareTo;
        if (job.Name == jobsWrapper.job.Name) return 0;
        if (job.Name > jobsWrapper.job.Name) return 1;
        return -1;        
    }
}

Then once you put your objects into a list you can use the sort method.

List<jobsWrapper> jobs = new List<jobsWrapper>();
// Add things to the list ...
jobs.sort();

Attribution
Source : Link , Question Author : Sushma Rao , Answer Author : Andrew Fawcett

Leave a Comment