谈起Java 8,不少熟悉它的人,都会知道有一个对我们帮助很大的新特性,没错,就是我们在项目中经常用到的stream,它对我们处理数据的过程中提供了很多的便利,而这边文章主要讲述stream的便利之一:对多个字段进行排序
- 首先我们在数据库中插入几条样例数据
要求:按照nick_name、address、age顺序进行排序
- 我们先用sql查询的方式对数据进行排序
通过stream流的方式进行排序
代码实现:
public Object selectList() { List<User> userList = userMapper.selectList(new QueryWrapper<>()); Comparator<User>comparator =Comparator.comparing(User::getNickName) .thenComparing(User::getAddress) .thenComparing(User::getAge); userList = userList.stream().sorted(comparator).collect(Collectors.toList()); return userList; }
结果展示:
[ { "id": 2, "userName": "zhangsan", "nickName": "张三", "password": "123456", "address": "武汉", "phone": "18178523659", "sex": 1, "age": 42, "createTime": "2023-07-15 13:30:52" }, { "id": 3, "userName": "zhangsan102", "nickName": "张三", "password": "123456", "address": "武汉", "phone": "15236985214", "sex": 1, "age": 57, "createTime": "2023-07-15 13:31:27" }, { "id": 4, "userName": "zhangshan103", "nickName": "张三", "password": "123456", "address": "西安", "phone": "18956235841", "sex": 1, "age": 36, "createTime": "2023-07-15 13:32:28" }, { "id": 1, "userName": "admin", "nickName": "超级管理员", "password": "123456", "address": "武汉", "phone": "15172378154", "sex": 1, "age": 30, "createTime": "2023-05-08 11:45:31" }]
通过代码我们可以知道通过stream的sorted()方法就可实现我们想要的结果,原理还是利用Comparator比较器对要排序的字段进行比较,如果想倒序,则在比较器后面加上reversed(),该方法是对排序后的数据进行一个反转。
小结:虽然对多个字段进行排序有时候通过sql语句就能实现,但有时候一些特殊场景导致不能使用sql排序的时候,stream就能派上用场了
来源地址:https://blog.csdn.net/qq_42570879/article/details/131738318