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.
This should work:
public class StudentsComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
final int nameComparison = s1.getName().compareToIgnoreCase(s2.getName());
if (nameComparison != 0) {
return nameComparison;
}
return Integer.compare(s1.getAge(), s2.getAge());
}
}
You can also make Student
comparable:
public class Student implements Comparable<Student> {
String name;
int age;
String hobby;
@Override
public int compareTo(Student other) {
final int nameComparison = name.compareToIgnoreCase(other.name);
if (nameComparison != 0) {
return nameComparison;
}
return Integer.compare(age, other.age);
}
}