Alex M Alex M - 1 year ago 74
Java Question

Sorting objects by multiple attributes

I've been working on something that requires me to sort objects (Soft drinks) by three attributes -

name (str)
colour (str)
volume (int)
. I've researched around and found ways to order them by name and colour and volume separately, but is there a way to order them by all three?

By which I mean: For example, say there are four SoftDrink objects: Fanta Orange 500, Coke Red 500, Coke Silver 500 Fanta Orange 400.

The output I'm looking for would be:

  • 1) Coke Red 500

  • 2) Coke Silver 500

  • 3) Fanta Orange 400

  • 4) Fanta Orange 500

Sort by name first, then colour, then volume (ascending).

I'm using three Comparators currently:
, and
, but each of them sorts the objects by name only, then by colour only, then by volume only. Is it possible to sort according to multiple attributes with Comparator?

Answer Source

Try something like this:


Remember to have getters for your attributes (getName, getColour etc.). This is all you need, no need for any custom comparators or anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download