The object we are going to sort is a Person.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Person { public enum Gender {FEMALE, MALE}; private String name; private Integer age; private Gender gender; public Person(String name, Integer age, Gender gender) { this.name = name; this.age = age; this.gender = gender; } //getter, setter, equals(...), and hashCode() methods skipped @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]"; } } |
Option 1: Writing your own Comparator implementation. This can be done as an anonymous inner class instead of a separate class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Comparator; public class PersonComparator implements Comparator<Person> { @Override public int compare(Person o1, Person o2) { //by gender first int i1 = o1.getGender().compareTo(o2.getGender()); if (i1 != 0) return i1; //by name next int i2 = o1.getName().compareTo(o2.getName()); if (i2 != 0) return i2; //by age return o1.getAge().compareTo(o2.getAge()); } } |
The test class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.ArrayList; import java.util.List; public class PersonTest { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("John", 35, Person.Gender.MALE)); people.add(new Person("John", 32, Person.Gender.MALE)); people.add(new Person("Simone", 30, Person.Gender.FEMALE)); people.add(new Person("Shawn", 30, Person.Gender.MALE)); System.out.println("before sorting = " + people); people.sort(new PersonComparator()); System.out.println("after sorting = " + people); } } |
Option 2: The…