0%

java根据对象属性排序

Collections.sort() Comparable对象

1
2
3
public class User implements Comparable<User> {

}

排序

1
2
Collections.sort(users);
Collections.reverse(users);

Collections.sort() 传入Comparator比较器

1
2
3
4
5
6
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
return u1.getCreatedOn().compareTo(u2.getCreatedOn());
}
});

List接口的sort

1
2
users.sort(Comparator.comparing(User::getCreatedOn));
users.sort(Comparator.comparing(User::getCreatedOn).reversed());

Stream接口的sorted [Java8]

1
2
3
4
5
6
7
List<User> sortedUsers = users.stream()
.sorted(Comparator.comparing(User::getCreatedOn))
.collect(Collectors.toList());

List<User> sortedUsers = users.stream()
.sorted(Comparator.comparing(User::getCreatedOn).reversed())
.collect(Collectors.toList());