I have a collection of Duck objects, and I would like to sort them with a few keys .
class Duck { DuckAge age;
eg. I want to sort them first by their weights and a second time by age . If two ducks have the same weight and exact age, then let them differentiate them using their names as a tertiary key . I could do something like this:
Collections.sort(ducks, new Comparator<Duck>(){ @Override public int compare(Duck d1, Duck d2){ int weightCmp = d1.weight.compareTo(d2.weight); if (weightCmp != 0) { return weightCmp; } int ageCmp = d1.age.compareTo(d2.age); if (ageCmp != 0) { return ageCmp; } return d1.name.compareTo(d2.name); } });
Well, I do this quite often, but this solution doesn't smell right. It does not scale well and is easy to spoil. Of course, there should be a better way to sort ducks with just a few keys! Does anyone know of a better solution?
EDIT removed unnecessary else branches
java sorting comparator comparable
andras Nov 07 '11 at 12:22 2011-11-07 12:22
source share