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; 

1 Answer 1


You can declare a constant list of mappings to numbers based on these values, eg:

public class Wrapper implements Comparable{
    public const colorMap Map<String,Integer> = new Map<String,Integer> {'Green'=>0, 'Yellow'=> '1','Red'=> '2'}
    .... rest of your class

Then in the comparable method, you use the map to get numeric values for your colors:

public Integer compareTo(Object compareTo){
    Wrapper wrap = (Wrapper) compareTo;
    Integer compareToInt = colorMap.get(wrap.c.Custom_Field__c);
    Integer thisInt = colorMap.get(c.Custom_Field__c);

    if (thisInt == compareToInt) return 0;
    if (thisInt > compareToInt) return 1;
    return -1

Of course, you may want to reverse the value or change the order - this can all be done in the constant map.

@sfdcfox adds a very nice and more concise method here:

return compareToInt-thisInt;
  • 2
    I was in the process of writing that, but you really should have just said: return compareToInt-thisInt;
    – sfdcfox
    Jan 13, 2016 at 21:14
  • 1
    Nice - that'd work :) - I'll add that to the answer. Jan 13, 2016 at 21:15
  • 1
    As a one-liner: return colorMap.get(((Wrapper)compareTo).c.Custom_Field__c)-colorMap.get(c.Custom_Field__c);
    – sfdcfox
    Jan 13, 2016 at 21:18
  • Haha even nicer - assuming your get works every time. Jan 13, 2016 at 21:19
  • @CasparHarmer Thanks guys! I really appreciate it. Clean, concise solution. Jan 13, 2016 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.