ComparisonChain.compare(...) should support lazy arguments passing
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.
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??
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);