Sorting Lists of sObjects

Using the List.sort method, you can sort lists sObjects.

For sObjects, sorting is in ascending order and uses a sequence of comparison steps outlined in the next section. Alternatively, you can also implement a custom sort order for sObjects by wrapping your sObject in an Apex class and implementing the Comparable interface, as shown in Custom Sort Order of sObjects.

Default Sort Order of sObjects

The List.sort method sorts sObjects in ascending order and compares sObjects using an ordered sequence of steps that specify the labels or fields used. The comparison starts with the first step in the sequence and ends when two sObjects are sorted using specified labels or fields. The following is the comparison sequence used:
  1. The label of the sObject type.

    For example, an Account sObject will appear before a Contact.

  2. The Name field, if applicable.

    For example, if the list contains two accounts named A and B respectively, account A comes before account B.

  3. Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields.

    For example, if two accounts have the same name, the first standard field used for sorting is AccountNumber.

  4. Custom fields, starting with the fields that come first in alphabetical order.

    For example, suppose two accounts have the same name and identical standard fields, and there are two custom fields, FieldA and FieldB, the value of FieldA is used first for sorting.

Not all steps in this sequence are necessarily carried out. For example, if a list contains two sObjects of the same type and with unique Name values, they’re sorted based on the Name field and sorting stops at step 2. Otherwise, if the names are identical or the sObject doesn’t have a Name field, sorting proceeds to step 3 to sort by standard fields.

For text fields, the sort algorithm uses the Unicode sort order. Also, empty fields precede non-empty fields in the sort order.

This is an example of sorting a list of Account sObjects. This example shows how the Name field is used to place the Acme account ahead of the two sForce accounts in the list. Since there are two accounts named sForce, the Industry field is used to sort these remaining accounts because the Industry field comes before the Site field in alphabetical order.

Account[] acctList = new List<Account>();        
acctList.add( new Account(
    Name='sForce',
    Industry='Biotechnology',
    Site='Austin'));
acctList.add(new Account(
    Name='sForce',
    Industry='Agriculture',
    Site='New York'));
acctList.add(new Account(
    Name='Acme'));
System.debug(acctList);

acctList.sort();
System.assertEquals('Acme', acctList[0].Name);
System.assertEquals('sForce', acctList[1].Name);
System.assertEquals('Agriculture', acctList[1].Industry);
System.assertEquals('sForce', acctList[2].Name);
System.assertEquals('Biotechnology', acctList[2].Industry);
System.debug(acctList);

This example is similar to the previous one, except that it uses the Merchandise__c custom object. This example shows how the Name field is used to place the Notebooks merchandise ahead of Pens in the list. Since there are two merchandise sObjects with the Name field value of Pens, the Description field is used to sort these remaining merchandise items because the Description field comes before the Price and Total_Inventory fields in alphabetical order.

Merchandise__c[] merchList = new List<Merchandise__c>();        
merchList.add( new Merchandise__c(
    Name='Pens',
    Description__c='Red pens',
    Price__c=2,
    Total_Inventory__c=1000));
merchList.add( new Merchandise__c(
    Name='Notebooks',
    Description__c='Cool notebooks',
    Price__c=3.50,
    Total_Inventory__c=2000));
merchList.add( new Merchandise__c(
    Name='Pens',
    Description__c='Blue pens',
    Price__c=1.75,
    Total_Inventory__c=800));
System.debug(merchList);

merchList.sort();
System.assertEquals('Notebooks', merchList[0].Name);
System.assertEquals('Pens', merchList[1].Name);
System.assertEquals('Blue pens', merchList[1].Description__c);
System.assertEquals('Pens', merchList[2].Name);
System.assertEquals('Red pens', merchList[2].Description__c);
System.debug(merchList);

Custom Sort Order of sObjects

To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify the sort logic.

This example shows how to create a wrapper class for Opportunity. The implementation of the compareTo method in this class compares two opportunities based on the Amount field—the class member variable contained in this instance, and the opportunity object passed into the method.

global class OpportunityWrapper implements Comparable {

    public Opportunity oppy;
    
    // Constructor
    public OpportunityWrapper(Opportunity op) {
        oppy = op;
    }
    
    // Compare opportunities based on the opportunity amount.
    global Integer compareTo(Object compareTo) {
        // Cast argument to OpportunityWrapper
        OpportunityWrapper compareToOppy = (OpportunityWrapper)compareTo;
        
        // The return value of 0 indicates that both elements are equal.
        Integer returnValue = 0;
        if (oppy.Amount > compareToOppy.oppy.Amount) {
            // Set return value to a positive value.
            returnValue = 1;
        } else if (oppy.Amount < compareToOppy.oppy.Amount) {
            // Set return value to a negative value.
            returnValue = -1;
        }
        
        return returnValue;       
    }
}

This example provides a test for the OpportunityWrapper class. It sorts a list of OpportunityWrapper objects and verifies that the list elements are sorted by the opportunity amount.

@isTest 
private class OpportunityWrapperTest {
    static testmethod void test1() {
        // Add the opportunity wrapper objects to a list.
        OpportunityWrapper[] oppyList = new List<OpportunityWrapper>();
        Date closeDate = Date.today().addDays(10);
        oppyList.add( new OpportunityWrapper(new Opportunity(
            Name='Edge Installation',
            CloseDate=closeDate,
            StageName='Prospecting',
            Amount=50000)));
        oppyList.add( new OpportunityWrapper(new Opportunity(
            Name='United Oil Installations',
            CloseDate=closeDate,
            StageName='Needs Analysis',
            Amount=100000)));
        oppyList.add( new OpportunityWrapper(new Opportunity(
            Name='Grand Hotels SLA',
            CloseDate=closeDate,
            StageName='Prospecting',
            Amount=25000)));
        
        // Sort the wrapper objects using the implementation of the 
        // compareTo method.
        oppyList.sort();
        
        // Verify the sort order
        System.assertEquals('Grand Hotels SLA', oppyList[0].oppy.Name);
        System.assertEquals(25000, oppyList[0].oppy.Amount);
        System.assertEquals('Edge Installation', oppyList[1].oppy.Name);
        System.assertEquals(50000, oppyList[1].oppy.Amount);
        System.assertEquals('United Oil Installations', oppyList[2].oppy.Name);
        System.assertEquals(100000, oppyList[2].oppy.Amount);
        
        // Write the sorted list contents to the debug log.
        System.debug(oppyList);
    }
}
Previous
Next