I'm trying to write a tiebreaker method in Java that will return an entry based on a value in a Comparator
. This is the abstract method:
protected abstract Comparator<Map.Entry<Team, Stats>> getLeagueTableEntryComparator();
Now I would like to separate the entries based on points, then goal difference, then goals scored. Here's the override method in a separate class, comparing by the appropriate fields:
@Override
protected Comparator<Map.Entry<Team, Stats>> getLeagueTableEntryComparator() {
return (Map.Entry<Team, Stats> teamStatsEntryOne, Map.Entry<Team, Stats> teamStatsEntryTwo) -> {
int compare = Integer.compare(teamStatsEntryOne.getValue().getPoints(),
teamStatsEntryTwo.getValue().getPoints());
if (compare == 0) {
compare = Integer.compare(teamStatsEntryOne.getValue().getTotalGoalDifference(),
teamStatsEntryTwo.getValue().getTotalGoalDifference());
if (compare == 0) {
compare = Integer.compare(teamStatsEntryOne.getValue().getGoalsFor(),
teamStatsEntryTwo.getValue().getGoalsFor());
}
return compare;
};
}
However, it's clear that it is possible for compare
to be zero at the end, even after having compared each field.
My question is this- what is the actual behaviour of the Comparator if comparator=0
at the end? Will I need to write a number generator at the end to achieve a "true" random 50/50 pick between the two entries?
If the comparator returns 0, the two entries are considered equivalent. It's then up to you to decide what to do with this knowledge - you could randomly choose between the two equivalent elements, or just apply the same treatment to each (e.g., in this usecase, if the two teams are indistinguishable from each other, you could decide to randomly choose between them, declare them as co-champions, or even decide that they should play a tie-breaker game).
Note that you should never introduce a random part in the comparator's code though - this will cause the comparator's behavior to be non-deterministic, and violate the general comparator contract.