Alex M Alex M - 2 months ago 13
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)
and
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:
nameComparator
,
colourComparator
, and
volumeComparator
, 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

Try something like this:

drinks.sort(
      Comparator.comparing(Drink::getName).thenComparing(Drink::getColour).thenComparing(Drink::getVolume)
    );

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

Comments