Java – sort objects by multiple attributes
I've been studying things that require me to classify objects (soft drinks) according to three attributes - Software (STR), color (STR) and volume (int) I have studied and found a way to order them by name, color and volume, but is there any way to order them in three ways?
I mean: for example, suppose there are four softdrink objects: Fantasy orange 500, coke red 500, coke silver 500, and fantasy orange 400
The output I'm looking for will be:
Sort first by name, then by color, and then by volume (ascending)
I currently use three Comparators: namecomparator, colorcomparator and volumecompator, but each comparator sorts objects only by name, then only by color, and then by volume Can I use comparator to sort by multiple attributes?
Solution
Try something like this:
drinks.sort( Comparator.comparing(Drink::getName).thenComparing(Drink::getColour).thenComparing(Drink::getVolume) );
Remember to set getters (getname, getcolor, etc.) for your properties This is what you need without any custom comparators or anything