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
Create as many comparators as necessary. After, call the method "thenComparing" for each order category. It's a way of doing by Streams. See:
//Sort by first and last name
System.out.println("\n2.Sort list of person objects by firstName then "
+ "by lastName then by age");
Comparator sortByFirstName
= (p, o) -> p.firstName.compareToIgnoreCase(o.firstName);
Comparator sortByLastName
= (p, o) -> p.lastName.compareToIgnoreCase(o.lastName);
Comparator sortByAge
= (p, o) -> Integer.compare(p.age,o.age);
//Sort by first Name then Sort by last name then sort by age
personList.stream().sorted(
sortByFirstName
.thenComparing(sortByLastName)
.thenComparing(sortByAge)
).forEach(person->
System.out.println(person));
Look: Sort user defined object on multiple fields – Comparator (lambda stream)