How to sort by two fields in Java?

后端 未结 16 2295
离开以前
离开以前 2020-11-22 08:40

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

16条回答
  •  情书的邮戳
    2020-11-22 09:24

    I'm not sure if it's ugly to write the compartor inside the Person class in this case. Did it like this:

    public class Person implements Comparable  {
    
        private String lastName;
        private String firstName;
        private int age;
    
        public Person(String firstName, String lastName, int BirthDay) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = BirthDay;
        }
    
        public int getAge() {
            return age;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        @Override
        public int compareTo(Person o) {
            // default compareTo
        }
    
        @Override
        public String toString() {
            return firstName + " " + lastName + " " + age + "";
        }
    
        public static class firstNameComperator implements Comparator {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.firstName.compareTo(o2.firstName);
            }
        }
    
        public static class lastNameComperator implements Comparator {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.lastName.compareTo(o2.lastName);
            }
        }
    
        public static class ageComperator implements Comparator {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.age - o2.age;
            }
        }
    }
    public class Test {
        private static void print() {
           ArrayList list = new ArrayList();
            list.add(new Person("Diana", "Agron", 31));
            list.add(new Person("Kay", "Panabaker", 27));
            list.add(new Person("Lucy", "Hale", 28));
            list.add(new Person("Ashley", "Benson", 28));
            list.add(new Person("Megan", "Park", 31));
            list.add(new Person("Lucas", "Till", 27));
            list.add(new Person("Nicholas", "Hoult", 28));
            list.add(new Person("Aly", "Michalka", 28));
            list.add(new Person("Adam", "Brody", 38));
            list.add(new Person("Chris", "Pine", 37));
            Collections.sort(list, new Person.lastNameComperator());
            Iterator it = list.iterator();
            while(it.hasNext()) 
                System.out.println(it.next().toString()); 
         }  
    }    
    

提交回复
热议问题