How to sort by two fields in Java?

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

    Have your person class implement Comparable 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.

提交回复
热议问题