Skip to main content
Tweeted twitter.com/StackSalesforce/status/688808039026130945
edited title
Link
cropredy
  • 73.2k
  • 8
  • 128
  • 283

Wrapper class sorting where sort is not lexicographical

Source Link
Antonio Manente
  • 1.5k
  • 1
  • 15
  • 25

Wrapper class sorting

I've seen a couple of questions regarding sorting a Wrapper class, but I don't believe any meet my requirements. (Please correct me if I'm wrong) So I've implemented sorting for my wrapper class, and it's working fine sorting my specified class in alphabetical order.

My requirement is to sort by a separate order. The field I am sorting by has three possible values [Red, Green, Yellow]. Currently, my sort() method returns in alphabetical order of these fields [Green, Red, yellow]. I'm wondering how to implement sorting by my own specified parameters (In this case, sort in the order [Green, Yellow, Red]). Is this possible given my implementation? Any help/nudge in the right direction is greatly appreciated. Here is my wrapper class currently:

public class Wrapper implements Comparable{
    public Case c{get;set;}
    public Account acc{get;set;}
    public Wrapper(Case c, Account a){
        this.c = c;
        this.acc = a;
    }

    public Integer compareTo(Object compareTo){
        Wrapper wrap = (Wrapper) compareTo;
        if (c.Custom_Field__c == wrap.c.Custom_Field__c) return 0;
        if (c.Custom_Field__c > wrap.c.Custom_Field__c) return 1;
        return -1; 
    }
}