//按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' }]