使用Java提供的流API提升代码质量,此次分享排序
先上示例代码,如下
import lombok.Data;
@Data
public class User {
private String name;
private Integer age;
private Integer schoolNumber;
}
写一个main,需求:按照年龄,由低到高排序
public class SortDemo {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User user1 = new User();
User user2 = new User();
User user3 = new User();
user1.setAge(18);
user2.setAge(16);
user3.setAge(17);
user1.setName("人物1");
user2.setName("人物2");
user3.setName("人物3");
user1.setSchoolNumber(88);
user2.setSchoolNumber(99);
user3.setSchoolNumber(100);
list.add(user1);
list.add(user2);
list.add(user3);
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
users.forEach(System.out::println);
}
}
结果如下图:
需求2:按照年龄倒叙排序
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder()))
.collect(Collectors.toList());
users.forEach(System.out::println);
结果如下图:
需求3:按照年龄、学号排序
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge)
.thenComparing(User::getSchoolNumber))
.collect(Collectors.toList());
结果如下图:
需求4:按照年龄倒叙、学号排序
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())
.thenComparing(User::getSchoolNumber))
.collect(Collectors.toList());
结果如下图:
需求5:按照年龄倒叙、学号倒叙 排序
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())
.thenComparing(User::getSchoolNumber,Comparator.reverseOrder()))
.collect(Collectors.toList());
结果如下图:
最后,对结果先排序,最后分页
List<User> users = list.stream()
.sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())
.thenComparing(User::getSchoolNumber,Comparator.reverseOrder()))
.skip((long)((currentPage - 1) * pageSize))
.limit(pageSize)
.collect(Collectors.toList());