How would you compare a custom object by a String field and an int field?
For example:
public class person implements Comparable<Person> {
String name;
int age;
@Override
public int compareTo(@NonNull Person another) {
return name.compareToIgnoreCase(another.name);
}
}
As you can expect, this works well and sorts the person objects in ascending order by name.
My problem: I also want to sort the list of Person objects by their age as well.
When it is sorted, the List should look like this:
name = a, age = 18
name = b, age = 18
name = c, age = 18
name = a, age = 20
name = b, age = 20
name = c, age = 20
...and so on...
First, check your primary attributes. If these are equal, check the secondary attributes:
@Override
public int compareTo(@NonNull Person another) {
int result = Integer.compare(age, another.age);
if (result == 0) {
result = name.compareToIgnoreCase(another.name);
}
return result;
}
For pre-1.7 Java versions – the manual way:
@Override
public int compareTo(@NonNull Person another) {
if (age == another.age) {
return name.compareToIgnoreCase(another.name);
} else if (age < another.age) {
return -1;
} else {
return 1;
}
}