Hello, I came across such a problem that you need to sort the ArrayList by two parameters, by the name of the owner and by the price of the room.

At the moment, this is how the room looks like

class Room { String Name; String Surname; String RoomS; int RoomN; int RoomQ; float cost; Room(String Name,String Surname,String RoomS,int RoomN,int RoomQ,float cost) { this.Name=Name; this.Surname=Surname; this.RoomS=RoomS; this.RoomN=RoomN; this.RoomQ=RoomQ; this.cost=cost; }} 

All this data is read from the file. At the moment, I only managed to compare the price. And it is necessary to compare both the owner's name and the price of the room at the same time.

This is my comparator at the moment.

 Collections.sort(r, new Comparator<Room>() { @Override public int compare(Room r1, Room r2) { int result = (int) (r2.cost - r1.cost); if(result != 0) { return result; } return 0; } }); 

No idea how to do it.

Added later to the class room

 public String getName() { return Name; } 

And the code that was suggested below has earned.

    1 answer 1

     Collections.sort(r, new Comparator<Room>() { @Override public int compare(Room r1, Room r2) { int result = (int) (r2.cost - r1.cost); if(result != 0) { return result; }else{ return r1.getName().compareTo(r2.getName()); } } }); 

    you lacked just 1 block else . First, you compare the price, if 0 is returned (the prices are equal), then you return the result of the comparison of names (no matter what).

    • I emphasize in red what is written in the else block - TiPSY
    • yes, wrong with the method. do not compare and compareTo - Victor
    • I added this to the room class public String getName () {return Name; } True, it seems to me that he still sorts by value - TiPSY
    • If sorting is used in different pieces of code and it’s the same, then implements Comparable is better - bench_doos