【List伪分页代码】
1、自定义分页
请求参数:
@PathVariable Integer pageNo,@PathVariable Integer pageSize
int totalSize = queryList.size();
int totalPage = totalSize % pageSize ==0 ? totalSize /pageSize:(totalSize % pageSize) +1;
if(totalPage > 1 ){
// 0,10 11,20
int fromIndex = 0; // 开始索引
int toIndex = 0; // 结束索引
if (pageNo != totalPage) {
fromIndex = (pageNo - 1) * pageSize;
toIndex = fromIndex + pageSize;
} else {
fromIndex = (pageNo - 1) * pageSize;
toIndex = totalSize;
}
// 50/1 每页数量不够,例如只有5条数据时候
if(toIndex > totalSize){
toIndex = totalSize;
}
//5/100 总页数不够的情况
if(fromIndex > totalSize){
fromIndex = 0;
}
queryList = queryList.subList(fromIndex,toIndex);
return queryList;
}
2、使用分页组件
请求参数:pageNum,pageSize
public static <T> PageInfo<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
//创建Page类
com.github.pagehelper.Page page = new com.github.pagehelper.Page(pageNum, pageSize);
//为Page类中的total属性赋值
page.setTotal(list.size());
//计算当前需要显示的数据下标起始值
int startIndex = (pageNum - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, list.size());
//从链表中截取需要显示的子链表,并加入到Page
page.addAll(list.subList(startIndex,endIndex));
//以Page创建PageInfo
PageInfo pageInfo = new PageInfo<>(page);
return pageInfo;