guava icon indicating copy to clipboard operation
guava copied to clipboard

ComparisonChain.compare(...) should support lazy arguments passing

Open adaslaf opened this issue 6 years ago • 1 comments

Another compare method should be added to ComparisonChain class to support lazy arguments passing.

Sample code:

      int result = ComparisonChain.start()
                .compare(e1.cheapCalculation(), e2.cheapCalculation())
                .compare(e1.expensiveCalculation(), e2.expensiveCalculation())
                .result();

In this sample 2 calls to expensiveCalculation() will be executed even when the ComparisonChain result is already calculated earlier.

In such cases I would like to have a possibility to use Java Suppliers - I mean something like this:

        int result = ComparisonChain.start()
                .compare(e1.cheapCalculation(), e2.cheapCalculation())
                .compare(() -> e1.expensiveCalculation(), () -> e2.expensiveCalculation())
                .result();

... to avoid expensive calculation where they are not needed.

adaslaf avatar Aug 29 '19 15:08 adaslaf

Hi @adaslaf @kluever this seems a nice problem to solve and I am also a beginner in this repo, so can I please take this up??

dwibedis avatar Sep 07 '19 11:09 dwibedis

As #6173 says, ComparisonChain is mostly obsolete. Using the static Comparator methods allows what's asked for here. Instead of:

        int result = ComparisonChain.start()
                .compare(e1.cheapCalculation(), e2.cheapCalculation())
                .compare(() -> e1.expensiveCalculation(), () -> e2.expensiveCalculation())
                .result();

you can do:

  private static final Comparator<Foo> COMPARATOR =
      Comparator.comparing(Foo::cheapCalculation)
          .thenComparing(Foo::expensiveCalculation);

  ...
      int result = COMPARATOR.compare(e1, e2);

eamonnmcmanus avatar Sep 27 '22 21:09 eamonnmcmanus