Java对组装的List分页
以前一直是在DAO层直接从数据库里分页,但是今天因为有些数据,需要混合展示,就是根据条件取出了多个对象的集合,然后把这些多个List放到一个List里,然后在从这个List里进行分页。
public SearchResult paging(List<T> list, int pageNumber, int pageSize) throws Exception{
List<T> pageList = new ArrayList<T>();
int currIdx = (pageNumber > 1 ? (pageNumber -1) * pageSize : 0);
for (int i = 0; i < pageSize && i < list.size() - currIdx; i++){
T listNew = list.get(currIdx + i);
pageList.add(listNew);
}
SearchResult<T> searchResult = new SearchResult<>();
searchResult.setList(pageList);
searchResult.setTotal(list.size());
if (searchResult.getTotal()%pageSize == 0){
searchResult.setPages((int)searchResult.getTotal()/pageSize);
}else {
searchResult.setPages((int)searchResult.getTotal()/pageSize + 1);
}
searchResult.setPageNum(pageNumber);
searchResult.setPageSize(pageSize);
searchResult.setSize(pageList.size());
//是否是第一页
if (pageNumber == 1){
searchResult.setIsFirstPage(true);
}else {
searchResult.setIsFirstPage(false);
}
//是否是最后一页
if ((searchResult.getTotal() - pageNumber*pageSize) > 0){
searchResult.setIsLastPage(false);
}else {
searchResult.setIsLastPage(true);
}
return searchResult;
}