This is an acceptable way to code. The compiler will make your implementation of the Comparator
interface into a class. Because you don't provide a name for the class, this is called an anonymous class.
I have no issue with the use of anonymous classes, but I prefer to use a variable, for an instance of an anonymous class. This gives you the opportunity to supply a name that says what kind of comparison your comparator will do. In this case, I might write something like this.
Comparator<Map.Entry<String, Integer>> byValueDescendingThenKey =
new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
int valueComparison = entry1.getValue().compareTo(entry2.getValue());
if (valueComparison != 0) {
return -valueComparison;
} else {
return entry1.getKey().compareTo(entry2.getKey());
}
}
};
Collections.sort(list,byValueDescendingThenKey);
Notice how if there is a nice descriptive name for the variable that references the Comparator
, the line that does the sorting is much clearer.