How to sort by two fields in Java?

后端 未结 16 1977
离开以前
离开以前 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 08:57

    You need to implement your own Comparator, and then use it: for example

    Arrays.sort(persons, new PersonComparator());
    

    Your Comparator could look a bit like this:

    public class PersonComparator implements Comparator {
    
      public int compare(Person p1, Person p2) {
         int nameCompare = p1.name.compareToIgnoreCase(p2.name);
         if (nameCompare != 0) {
            return nameCompare;
         } else {
           return Integer.valueOf(p1.age).compareTo(Integer.valueOf(p2.age));
         }
      }
    }
    

    The comparator first compares the names, if they are not equals it returns the result from comparing them, else it returns the compare result when comparing the ages of both persons.

    This code is only a draft: because the class is immutable you could think of building an singleton of it, instead creating a new instance for each sorting.

提交回复
热议问题