Collections.sort 多个字段排序
按年龄升序,工资升序
@Test
public void sortTest(){
List<User> users = new ArrayList<>();
users.add(new User("bob",120,10));
users.add(new User("tom",50,50));
users.add(new User("tom2",50,10));
users.add(new User("jerry",150,2));
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
int i = o1.getAge().compareTo(o2.getAge());
if (i==0){
return o1.getSalary().compareTo(o2.getSalary());
}
return i;
}
});
System.out.println(users);
}
@Data
@AllArgsConstructor
class User{
private String name;
private Integer age;
private Integer salary;
}
结果:
[
FinallyTest.User(name=tom2, age=50, salary=10),
FinallyTest.User(name=tom, age=50, salary=50),
FinallyTest.User(name=bob, age=120, salary=10),
FinallyTest.User(name=jerry, age=150, salary=2)
]