Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects by multiple attributes

Tags:

java

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?

like image 985
Paul12596 Avatar asked Dec 30 '25 21:12

Paul12596


1 Answers

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.

like image 99
Shadov Avatar answered Jan 02 '26 10:01

Shadov