5

I dont know how to sort a list of SObject Case.

I have a List<Case> newCases which i iterate over in for cycle, where i save Cases to my new List<Case> casesList.

for (Case newCase : newCases) {
            if(newCase.Case_Content__c == '111' && newCase.Status == '24'){
                String cuid = newCase.CUID__c;
                cuidSet.add(cuid);
                casesList.add(newCase);
                casesList.sort(); //TODO sorting by CUID__c
            }
        }

What i need to do is, to sort this new list by field CUID__c. So the Cases with same CUID are together.

Thank you for any help :)

1

3 Answers 3

16

You have to implement a Wrapper class with comparable interface for this to happen.

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.

Eg:

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;       
    }
}

And then to Sort just call Sort Method after adding records to your wrapper 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();

So in your case, the CaseWrapper will compare CUID__c to determine sorting order in the compareTo method.

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm

2

You can query the Cases again Where Ids IN: casesList, then Order BY CUID__c ASC/DESC. Yeah this is funny but it works.

Cheers!

2

In 2024 things have improved. Salesforce introduced the Comparator interface, something that Java had at least since version 1.2. No need for wrappers or another query. In order to sort according to a field CUID__c of the Case object, you'd implement a class like this:

public class CaseCUIDComparator implements Comparator<Case> {
    public Integer compare(Case case0, Case case1) {
        if(case0.CUID__c == null) return 1;
        if(case1.CUID__c == null) return -1;
        return case0.CUID__c < case1.CUID__c ? -1 : 1;
    }
}

The unit test demonstrates its use and its impact:

@IsTest
private static void verifyComparator() {
    List<Case> cases = new List<Case>{
        new Case(CUID__c = 'B'),
        new Case(CUID__c = null),
        new Case(CUID__c = 'A'),
        new Case(CUID__c = 'D'),
        new Case(CUID__c = 'A'),
        new Case(CUID__c = 'C')
    };

    Test.startTest();
    cases.sort(new CaseCUIDComparator());
    Test.stopTest();

    Assert.areEqual('A', cases[0].CUID__c);
    Assert.areEqual('A', cases[1].CUID__c);
    Assert.areEqual('B', cases[2].CUID__c);
    Assert.areEqual('C', cases[3].CUID__c);
    Assert.areEqual('D', cases[4].CUID__c);
    Assert.areEqual(null, cases[5].CUID__c);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .