How to sort by two fields in Java?

后端 未结 16 2215
离开以前
离开以前 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 users = Lists.newArrayList(
      new User("Pedro", 12), 
      new User("Maria", 10), 
      new User("Rafael",12)
    );
    
    users.sort(
      Comparator.comparing(User::getName).thenComparing(User::getAge)
    );
    

提交回复
热议问题