传入一个List集合,返回分页好的数据
传入一个List集合,返回分页好的数据。
定义分页信息类:
package com.cn.common;
import java.util.List;
public class CommonPage<T> {
private int currentPage;
private int totalPage;
private int pageSize;
private java.util.List<T> list;
public CommonPage (int currentPage, int totalPage, int pageSize, List<T> list) {
this.currentPage = currentPage;
this.totalPage = totalPage;
this.pageSize = pageSize;
this.list = list;
}
public CommonPage() {
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
给出总的List和页数,每页大小获取指定页数的数据。
public CommonPage<User> getPage(int pageNo,int pageSize,List<User> users){
//总页数
int totalCount = users.size();
// 计算分页数
int pageCount = (totalCount + pageSize - 1) / pageSize;
//计算从List中的开始索引
int startIndex = (pageNo - 1) * pageSize;
//计算从List中的结束索引
int endIndex = Math.min(startIndex + pageSize, totalCount);
//返回空
if (startIndex >= endIndex) {
return new CommonPage<User>(pageNo,totalCount,pageSize,Collections.emptyList());
}
//返回指定页数的数据
return new CommonPage<User>(pageNo,totalCount,pageSize,users.subList(startIndex, endIndex));
}
朋友和酒,少年和诗,路和远方。