I have array of objects person (int age; String name;)
.
How can I sort this array alphabetically by name and then by age?
Which algorithm would
You can use Collections.sort
as follows:
private static void order(List persons) {
Collections.sort(persons, new Comparator() {
public int compare(Object o1, Object o2) {
String x1 = ((Person) o1).getName();
String x2 = ((Person) o2).getName();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
Integer x1 = ((Person) o1).getAge();
Integer x2 = ((Person) o2).getAge();
return x1.compareTo(x2);
}});
}
List
is now sorted by name, then by age.
String.compareTo
"Compares two strings lexicographically" - from the docs.
Collections.sort
is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare
method.