How to sort by two fields in Java?

后端 未结 16 1957
离开以前
离开以前 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:10

    You can do like this:

    List<User> users = Lists.newArrayList(
      new User("Pedro", 12), 
      new User("Maria", 10), 
      new User("Rafael",12)
    );
    
    users.sort(
      Comparator.comparing(User::getName).thenComparing(User::getAge)
    );
    
    0 讨论(0)
  • 2020-11-22 09:11
    Arrays.sort(persons, new PersonComparator());
    
    
    
    import java.util.Comparator;
    
    public class PersonComparator implements Comparator<? extends Person> {
    
        @Override
        public int compare(Person o1, Person o2) {
            if(null == o1 || null == o2  || null == o1.getName() || null== o2.getName() ){
                throw new NullPointerException();
            }else{
                int nameComparisonResult = o1.getName().compareTo(o2.getName());
                if(0 == nameComparisonResult){
                    return o1.getAge()-o2.getAge();
                }else{
                    return nameComparisonResult;
                }
            }
        }
    }
    
    
    class Person{
        int age; String name;
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    Updated version:

    public class PersonComparator implements Comparator<? extends Person> {
    
       @Override
       public int compare(Person o1, Person o2) {
    
          int nameComparisonResult = o1.getName().compareToIgnoreCase(o2.getName());
          return 0 == nameComparisonResult?o1.getAge()-o2.getAge():nameComparisonResult;
    
       }
     }
    
    0 讨论(0)
  • 2020-11-22 09:12

    Using the Java 8 Streams approach...

    //Creates and sorts a stream (does not sort the original list)       
    persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
    

    And the Java 8 Lambda approach...

    //Sorts the original list Lambda style
    persons.sort((p1, p2) -> {
            if (p1.getName().compareTo(p2.getName()) == 0) {
                return p1.getAge().compareTo(p2.getAge());
            } else {
                return p1.getName().compareTo(p2.getName());
            } 
        });
    

    Lastly...

    //This is similar SYNTAX to the Streams above, but it sorts the original list!!
    persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
    
    0 讨论(0)
  • 2020-11-22 09:13

    Have your person class implement Comparable<Person> and then implement the compareTo method, for instance:

    public int compareTo(Person o) {
        int result = name.compareToIgnoreCase(o.name);
        if(result==0) {
            return Integer.valueOf(age).compareTo(o.age);
        }
        else {
            return result;
        }
    }
    

    That will sort first by name (case insensitively) and then by age. You can then run Arrays.sort() or Collections.sort() on the collection or array of Person objects.

    0 讨论(0)
  • 2020-11-22 09:13

    Or you can exploit the fact that Collections.sort() (or Arrays.sort()) is stable (it doesn't reorder elements that are equal) and use a Comparator to sort by age first and then another one to sort by name.

    In this specific case this isn't a very good idea but if you have to be able to change the sort order in runtime, it might be useful.

    0 讨论(0)
  • 2020-11-22 09:20

    Use Comparator and then put objects into Collection, then Collections.sort();

    class Person {
    
        String fname;
        String lname;
        int age;
    
        public Person() {
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getFname() {
            return fname;
        }
    
        public void setFname(String fname) {
            this.fname = fname;
        }
    
        public String getLname() {
            return lname;
        }
    
        public void setLname(String lname) {
            this.lname = lname;
        }
    
        public Person(String fname, String lname, int age) {
            this.fname = fname;
            this.lname = lname;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return fname + "," + lname + "," + age;
        }
    }
    
    public class Main{
    
        public static void main(String[] args) {
            List<Person> persons = new java.util.ArrayList<Person>();
            persons.add(new Person("abc3", "def3", 10));
            persons.add(new Person("abc2", "def2", 32));
            persons.add(new Person("abc1", "def1", 65));
            persons.add(new Person("abc4", "def4", 10));
            System.out.println(persons);
            Collections.sort(persons, new Comparator<Person>() {
    
                @Override
                public int compare(Person t, Person t1) {
                    return t.getAge() - t1.getAge();
                }
            });
            System.out.println(persons);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题