0

I have the following collection in my driver class:

ArrayList<SoftDrink> drinks = new ArrayList<>();

where SoftDrink has three private instance variable (there are accessor methods in the class):

String name;
String colour;
int volume;

Users are asked to input information about a drink and SoftDrink objects are added to the ArrayList like this:

drinks.add(new SoftDrink(drinkName, colour, volume));

When the user is done adding drinks I want the program to print out a list of the soft drinks that the user has entered, sorted first by alphabetical order of name, then by alphabetical order of colour, then by volume (in ascending order).

Example:

Coke Red 500
Coke Silver 500
Fanta Orange 300
Fanta Orange 500

What is the most Javaish way I could go about comparing these objects in the ArrayList and then sorting them approriately according to these various parameters?

aidandeno
  • 307
  • 1
  • 2
  • 16

1 Answers1

4

Maybe you can try something like this:

List<SoftDrink>  drinks= new ArrayList<SoftDrink>();

SoftDrink drink;
for(int i=0;i<numberOfDrinks;i++) {
  drink = new SoftDrink();
  drink.setname(...);
  drinks.add(drink);
}

//Sorting
Collections.sort(drinks, new Comparator<SoftDrink>() {
        @Override
        public int compare(SoftDrink  drink1, SoftDrink  drink2) {
            return  drink1.drinkName.compareTo(drink2.drinkName);
        }
    });
Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49
erad
  • 1,766
  • 2
  • 17
  • 26