Guava tips: ComparisonChain

Imagine you have a simple class with, say, three fields, and you have to make it Comparable. You will probably write a compareTo method similar to this:

public class MyTuple implements Comparable<MyTuple> {
    private final int x;
    private final String y;
    private final boolean z;

    @Override
    public int compareTo(MyTuple o) {
        int compareX = Integer.compare(x, y);
        if (compareX != 0) {
            return compareX;
        }
        int compareY = y.compareTo(o.y);
        if (compareY != 0) {
            return compareY;
        }
        return Boolean.compare(z, o.z);
    }

    // ...
}

Guava has a very useful class, ComparisonChain, to help you write these boring compareTo methods and make them much more readable. For instance, using it you could rewrite the above method as:

@Override
public int compareTo(MyTuple o) {
    return ComparisonChain.start()
            .compare(x, o.x)
            .compare(y, o.y)
            .compareFalseFirst(z, o.z)
            .result();
}

ComparisonChain is smart, in the sense that it will stop calling compareTo on objects as soon as it finds the first non zero comparison. It is much more readable, and less error prone. Highly recommended! :-)