3

I have created a wrapper which contains an account record and a string describing the level of account Platinum, Gold, Silver.

public class PartnerWrapper implements Comparable {
    public Account acc;
    public String level;
}

So how can I sort this wrapper list (using compareTo method as I have implemented my class with Comparable interface) first displaying results for Platinum, then Gold and then Silver?

If this cannot be achieved using Comparable interface, then please provide sample code snippet.

1 Answer 1

6
public class PartnerWrapper implements Comparable {
    private static final Map<String, Integer> levelsOrder = new Map<String, Integer>{
        'Platinum' => 1,
        'Gold' => 2,
        'Silver' => 3
        };
    public Account acc {get; set;}
    public String level {get; set;}

    public Integer compareTo(Object thatObj){
        PartnerWrapper that = (PartnerWrapper) thatObj;
        Integer thisOrder = defineLevelOrder(this.level);
        Integer thatOrder = defineLevelOrder(that.level);
        return thisOrder - thatOrder;
    }

    private Integer defineLevelOrder(String currentlevel){
        Integer result = 2147483647;
        if(levelsOrder.containsKey(currentlevel)){
            result = levelsOrder.get(currentlevel);
        }
        return result;
    }
}

You can control order by additional wrapper static field, that stores level and its order.

private static final Map<String, Integer> levelsOrder = new Map<String, Integer>{
    'Platinum' => 1,
    'Gold' => 2,
    'Silver' => 3
    };

Do not give field public access modifiers without properties, so I added properties as well.

If level is not in order defining field, than order of it is a max Integer apex value 2147483647. So unknown level values would be last after sorting

3
  • 2
    Since you're already doing Integer values, you could have simply said: return thisOrder - thatOrder; instead of all that if-else logic. It's not strictly required that you return -1, 0, and 1, just a negative value, 0 value, or positive value.
    – sfdcfox
    Commented Sep 20, 2017 at 13:07
  • @sfdcfox you are exactly right. I've updated code, thanks! Commented Sep 20, 2017 at 13:16
  • Well, this really seems some interesting stuff. It is working as described by Alexander, but I really need to understand the logic behind this in deep. Thanks man.
    – nica
    Commented Sep 20, 2017 at 16:24

You must log in to answer this question.

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