I have a wrapper class with 2 text values. I sorted them using Comparable. It works fine for one value.

Here, I have AreaName and ADName. With the below I'm able to successfully sort by AreaName. Now I want to sort with 2 values i.e., if AreaName is same, then sort by ADName. How?

global class AreaWrapper implements Comparable{
    public String AreaName{get;set;}
    public String ADName{get;set;}

    public AreaWrapper(){
        AreaName = '';
        ADName = '';

    global Integer compareTo(Object objToCompare) {
        //Sort by AreaName Alphabetically
        return AreaName.compareTo(((geoAreaWrapperInner)objToCompare).AreaName);


1 Answer 1


The value 0 is returned when the values are the same so for that case compare the other field:

global Integer compareTo(Object objToCompare) {
    AreaWrapper that = (AreaWrapper) objToCompare;
    Integer c = this.AreaName.compareTo(that.AreaName);
    if (c != 0) {
        return c;
    } else {
        return this.ADName.compareTo(that.ADName);

You must log in to answer this question.

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