Search code examples
javacomparator

How to understand the order induced by the comparator in Java?


I was so confused about comparator and Collections.sort() in Java. I don't understand the order induced by the comparator. I don't clear about which number the compare function should return to get the sorting direction. I also don't know how Collections will use that compare result to sort the input data. Should I learn them by heart? Is there anything easier to understand them? Can anybody explain it for me? Thanks.

public int compare(Obj a, Obj b){ 
    if(a.age > b.age) return 1; 
    if(a.age < b.age) return -1;
    else              return 0;
}

Update

After received some explanations from some friendly Software Engineer, I understood that the comparator define the order of elements in a Collections. For example, when compare a and b, if the comparator return -1 then a should be put before b in the list.


Solution

  • Step 1

    One way to simplify and correlate this could be that your code:

    public int compare(Obj a, Obj b){ 
        if(a.age > b.age) return 1; 
        if(a.age < b.age) return -1;
        else              return 0;
    }
    

    would be represented as following(given age is int variable)

    public int compare(Obj a, Obj b) {
        return Integer.compare(a.getAge(), b.getAge());
    }
    

    where Integer.compare internally does the same logic as you were doing previously:

    return (x < y) ? -1 : ((x == y) ? 0 : 1)
    

    Step 2

    Now this can further be represented using a comparator as:

    Comparator<Obj> ageComparator = Comparator.comparingInt(Obj::getAge);
    

    which Comparator.comparingInt internally performs

    return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    

    Hence the order eventually induced by all these three forms would be same when for example you would call

    objList.sort(ageComparator);
    

    Comparable's compareTo method can elaborate more on the part of comparison

    Compares this object with the specified object for order.  Returns a
    negative integer, zero, or a positive integer as this object is less
    than, equal to, or greater than the specified object.
    

    and hence that is considered to be the natural ordering of the Obj when you override the compareTo extending to a Comparable<Obj>.