使用說明:傳入3個參數
- list的集合;
- 前端請求的start本頁起始索引;
- 前端請求的pageSize每頁數量;
舉例說明:
- 假設list集合總數量total爲30條;
- 如果前端請求start爲0,每頁數量pageSize爲20條,那麼返回數據爲list集合中索引從0-19的20條數據;
- 如果前端請求start爲20,每頁數量pageSize爲20條,那麼返回數據爲list集合中索引從20-30條數據(總數爲30所以最多返回10條)。
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
/**
* 分頁輔助類
*
* @author sunjinxu
*
* @param <T>
*/
public class ListPageUtil<T> {
/** 原集合 */
private List<T> data;
/** 上一頁 */
private int lastPage;
/** 當前頁 */
private int nowPage;
/** 下一頁 */
private int nextPage;
/** 每頁條數 */
private int pageSize;
/** 總頁數 */
private int totalPage;
/** 總數據條數 */
private int totalCount;
public ListPageUtil(List<T> data, int start, int pageSize) {
if (data == null || data.isEmpty()) {
throw new IllegalArgumentException("data must be not empty!");
}
this.data = data;
this.pageSize = pageSize;
this.totalCount = data.size();
this.totalPage = (totalCount < pageSize) ? 1
: ((int) Math.ceil(Math.ceil((float) totalCount / (float) pageSize)));
this.nowPage = (start / pageSize) + 1;
this.lastPage = nowPage - 1 > 1 ? nowPage - 1 : 1;
this.nextPage = nowPage >= totalPage ? totalPage : nowPage + 1;
}
/**
* 得到分頁後的數據
*
* @param pageNum
* 頁碼
* @return 分頁後結果
*/
public List<T> getPagedList() {
int fromIndex = (nowPage - 1) * pageSize;
if (fromIndex >= data.size()) {
return Collections.emptyList();// 空數組
}
if (fromIndex < 0) {
return Collections.emptyList();// 空數組
}
int toIndex = nowPage * pageSize;
if (toIndex >= data.size()) {
toIndex = data.size();
}
List<T> pagedList= new ArrayList<T>();
for (T t : data.subList(fromIndex, toIndex)) {
pagedList.add(t);
}
return pagedList;
}
public int getPageSize() {
return pageSize;
}
public List<T> getData() {
return data;
}
public int getLastPage() {
return lastPage;
}
public int getNowPage() {
return nowPage;
}
public int getNextPage() {
return nextPage;
}
public int getTotalPage() {
return totalPage;
}
public int getTotalCount() {
return totalCount;
}
}