How to find which comparator “broke a tie” in a Guava order

I use the Guava Ordering class to sort the sort to select the "best" from this list. It looks something like this:

 // Create the Ordering, with a list of Comparators Ordering<String> ranker = Ordering.compound(ImmutableList.of( STRING_LENGTH, PERCENTAGE_UPPERCASE, NUMBER_OF_VOWELS)); // Use the ordering to find the 'best' from a list of Strings String best = ranker.max(asList("foo", "fooz", "Bar", "AEro")); 

With this Ordering string "AEro" is the best, because it is the longest, joint with "fooz", but tie-breaks with a higher percentage of characters in uppercase.

I’m looking for a way to find out which Comparator “broke a tie”, which in this silly far-fetched example would be the PERCENTAGE_UPPERCASE comparator.

I have a workable solution, but it is not particularly elegant and means duplication of the list of Comparator s. It should use Ordering to provide a sorted list ( Ordering.sortedCopy ), pulling the first two elements (range checking, of course), iterating through the List of the same Comparator s, comparing these two elements, breaking when the compareTo method returns a non-zero result.

Is there an easier way?

+4
source share
1 answer

Guava is here.

Your solution seems almost as good as you, but instead of making a sorted copy and pulling out the first two elements, you should make it more efficient

 List<E> best2 = ranker.greatestOf(list, 2); 

and then, indeed, iterating through the comparators, although you can probably reorganize to reuse the list of comparators from Ordering.compound rather than re-create it.

+3
source

All Articles