Java对List进行分页

Java对组装的List分页

以前一直是在DAO层直接从数据库里分页,但是今天因为有些数据,需要混合展示,就是根据条件取出了多个对象的集合,然后把这些多个List放到一个List里,然后在从这个List里进行分页。

 1 public SearchResult paging(List<T> list, int pageNumber, int pageSize) throws Exception{
 2         List<T> pageList = new ArrayList<T>();
 3         int currIdx = (pageNumber > 1 ? (pageNumber -1) * pageSize : 0);
 4         for (int i = 0; i < pageSize && i < list.size() - currIdx; i++){
 5             T listNew = list.get(currIdx + i);
 6             pageList.add(listNew);
 7         }
 8         SearchResult<T> searchResult = new SearchResult<>();
 9         searchResult.setList(pageList);
10         searchResult.setTotal(list.size());
11         if (searchResult.getTotal()%pageSize == 0){
12             searchResult.setPages((int)searchResult.getTotal()/pageSize);
13         }else {
14             searchResult.setPages((int)searchResult.getTotal()/pageSize + 1);
15         }
16         searchResult.setPageNum(pageNumber);
17         searchResult.setPageSize(pageSize);
18         searchResult.setSize(pageList.size());
19         //是否是第一页
20         if (pageNumber == 1){
21             searchResult.setIsFirstPage(true);
22         }else {
23             searchResult.setIsFirstPage(false);
24         }
25         //是否是最后一页
26         if ((searchResult.getTotal() - pageNumber*pageSize) > 0){
27             searchResult.setIsLastPage(false);
28         }else {
29             searchResult.setIsLastPage(true);
30         }
31         return searchResult;
32     }

 

posted @ 2018-02-02 16:23  低调的小白  阅读(2086)  评论(0编辑  收藏  举报