How to sort by two fields in Java?

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

    You can use Collections.sort as follows:

    private static void order(List persons) {
    
        Collections.sort(persons, new Comparator() {
    
            public int compare(Object o1, Object o2) {
    
                String x1 = ((Person) o1).getName();
                String x2 = ((Person) o2).getName();
                int sComp = x1.compareTo(x2);
    
                if (sComp != 0) {
                   return sComp;
                } 
    
                Integer x1 = ((Person) o1).getAge();
                Integer x2 = ((Person) o2).getAge();
                return x1.compareTo(x2);
        }});
    }
    

    List is now sorted by name, then by age.

    String.compareTo "Compares two strings lexicographically" - from the docs.

    Collections.sort is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare method.

提交回复
热议问题