How to sort by two fields in Java?

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

    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.

提交回复
热议问题