Reputation: 21
Say I do a search which returns a list of objects
{ age: 5, color: Yellow, eggs: 2 }
{ age: 3, color: White, eggs: 5 }
{ age: 4, color: Brown, eggs: 9 }
{ age: 2, color: Green, eggs: 4 }
{ age: 3, color: Red, eggs: 1 }
{ age: 1, color: Blue, eggs: 6 }
I would like to output them all, but in a particular order. If age is 3, I want these items first, sorted on most amount of eggs. Then I want the rest of the items sorted alphabetically on color.
So the sorted list would be
| 3's: eggs | rest: alphabetically on color |
White - Red - Blue - Brown - Green - Yellow
What is the best way to do this sorting, preferably without creating temporary lists?
Can it be done using a single Comparator, or using streams maybe?
Upvotes: 1
Views: 62
Reputation: 133975
You can do it with a single, kind of messy, Comparator. The idea is:
int compare(myType obj1, myType obj2)
{
// first compare age
if (obj1.age == 3)
{
if (obj2.age == 3)
{
// ages are both 3, so count eggs
return obj1.eggs.compareTo(obj2.eggs);
}
// age 3 sorts before everything else
return -1;
}
else if (obj2.age == 3)
{
// if obj2.age is 3, and obj1.age isn't 3,
// then obj1 is greater than obj2
return 1;
}
// compare color
return obj1.color.compareTo(obj2.color);
}
Please excuse any syntactical mistakes; my Java is a bit rusty.
Upvotes: 1
Reputation: 3455
Since Java 8, Comparator
has a few helpful static methods:
new AgeComparator().thenComparingInt(MyObj::getEggs).thenComparing(new ColorComparator());
Not sure what your class looks like - is that what you are asking for?
In general, I also like Apache Commons' CompareToBuilder for combining comparisions, but in your case it seems too limited.
Upvotes: 0