Let's say I have a List with Students: ArrayList<Student> student = new ArrayList<>();
. The Student-class looks like this:
public class Student {
String name;
int age;
String hobby;
//getter and Setter methods below
}
I want to sort that list by name, but if the names are equal, I want to sort it after the age. How can I do this in Java.
With this I can already sort it by name:
public class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if(o1.getName() > o2.getName()){
return 1;
}
else if(o1.getName() < o2.getName())
{
return -1;
}
else{
return 0;
}
}
}
So if they have the same name, how can I sort it after the age?
In the end I want to do Collections.sort(student, MyComparator comp)
to sort the list.