I have a class WHICH CANNOT implement comparable, but needs to be sorted based on 2 fields. How can I achieve this with Guava?
Let\'s say the class is:
c
Java 8 provides methods on Comparator to concisely specify chained comparators. Together with the newly-introduced List.sort, you can do:
lotsOfX.sort(
Comparator.comparingInt(x -> stringValueSortFunction.apply(x.stringValue))
.thenComparing(x -> x.dateValue, Comparator.reverseOrder()));
This mutates the list, of course -- make a copy first if you want to leave the original list unchanged, or wrap the comparator in an Ordering and use immutableSortedCopy
if you want an immutable copy.
I suspect you want Ordering.compound. You could do it all in one statement, but I'd use:
Ordering<X> primary = Ordering.natural().onResultOf(stringValueSortFunction);
Ordering<X> secondary = Ordering.natural()
.onResultOf(dateValueSortFunction)
.reverse();
Ordering<X> compound = primary.compound(secondary);
List<X> sortedList = compound.immutableSortedCopy(lotsOfX);
A less functional, but arguably cleaner, solution:
new Ordering<X>() {
public int compare(X x1, X x2) {
return ComparisonChain.start()
.compare(x1.stringValue, x2.stringValue)
.compare(x2.dateValue, x1.dateValue) // flipped for reverse order
.result();
}
}.immutableSortedCopy(listOfXs);