Class ComparisonChain

  • @GwtCompatible
    public abstract class ComparisonChain
    extends Object
    A utility for performing a chained comparison statement. For example:
     public int compareTo(Foo that) {
       return ComparisonChain.start()
           .compare(this.aString, that.aString)
           .compare(this.anInt, that.anInt)
           .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())

    The value of this expression will have the same sign as the first nonzero comparison result in the chain, or will be zero if every comparison result was zero.

    Note: ComparisonChain instances are immutable. For this utility to work correctly, calls must be chained as illustrated above.

    Performance note: Even though the ComparisonChain caller always invokes its compare methods unconditionally, the ComparisonChain implementation stops calling its inputs' compareTo and compare methods as soon as one of them returns a nonzero result. This optimization is typically important only in the presence of expensive compareTo and compare implementations.

    See the Guava User Guide article on ComparisonChain.

    Mark Davis, Kevin Bourrillion