❤️作者主页:温文尔雅的清欢渡
❤️ 近期学习方向:性能调优
❤️欢迎 点赞 收藏 ⭐ 留言 关注 ✌ 私聊我
工作中,会遇见对list对象进行排序的情况。
JAVA8用lamda表达式和增强版Comparator进行排序
List<Project> list = projectMapper.queryProjectDetailByCode(body.getProjectCode());
list.sort(Comparator.comparing(Project::getId));
list.sort(Comparator.comparing(Project::getId).reversed());
list.sort(Comparator.comparing(Project::getId).thenComparing(Project::getMoney));
list.sort(Comparator.comparing(Project::getId).thenComparing(Project::getMoney).reversed());
list.sort(Comparator.comparing(Project::getId).reversed().thenComparing(Project::getMoney).reversed());
list.sort(Comparator.comparing(Project::getId).reversed().thenComparing(Project::getMoney));
//dtoList -> 当前页所有数据
List<ProjectDTO> dtoList = list.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList()));
//总条数
dto.setPages(pageNo);
dto.setTotal(list.size());
dto.setList(dtoList);
skip:跳过n个元素,limit裁剪大小,pageNo 当前页,pageSize当前页大小。
当排序的属性值为null时,需要特殊处理,否则会报java.lang.NullPointerException
list.sort(Comparator.comparing(Project::getId,Comparator.nullsFirst(Integer::compareTo)));
list.sort(Comparator.comparing(Project::getId,Comparator.nullsLast(Integer::compareTo)));
list.sort(Comparator.comparing(Project::getId,Comparator.nullsFirst(Integer::compareTo)).reversed());
list.sort(Comparator.comparing(Project::getId,Comparator.nullsLast(Integer::compareTo)).reversed());