//按id从小到大
List<User> sortUser = list.stream().sorted((u1, u2) -> u1.getId().compareTo(u2.getId())).collect(Collectors.toList());
////按id从大到小
List<User> sortUser = list.stream().sorted((u1, u2) -> u2.getId().compareTo(u1.getId())).collect(Collectors.toList());
示例:
public class HelloWorld { public static void main(String[] args) {
List<User> list = new ArrayList<>();
for(int i=1;i<=10;i++) {
User u = new User(i, "用户-" + i);
list.add(u);
}
//按id从大到小排序
List<User> sortUser = list.stream().sorted((u1, u2) -> u2.getId().compareTo(u1.getId())).collect(Collectors.toList()); System.out.println("排序后:" + sortUser);
}
private static class User{
Integer id;
String name; public User(Integer id, String name) {
this.id = id;
this.name = name;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
} }
执行结果:
[User {
id = 10, name = '用户-10'
}, User {
id = 9, name = '用户-9'
}, User {
id = 8, name = '用户-8'
}, User {
id = 7, name = '用户-7'
}, User {
id = 6, name = '用户-6'
}, User {
id = 5, name = '用户-5'
}, User {
id = 4, name = '用户-4'
}, User {
id = 3, name = '用户-3'
}, User {
id = 2, name = '用户-2'
}, User {
id = 1, name = '用户-1'
}]