java如何對list進行分頁查詢---list分頁查詢工具類

工具類:ListPageUtil

package com.dt.user.center.util;

import java.util.Collections;
import java.util.List;


public class ListPageUtil<T> {
    private List<T> data;

    /** 上一頁 */
    private int lastPage;

    /** 當前頁 */
    private int currentPage;

    /** 下一頁 */
    private int nextPage;
//
    /** 每頁條數 */
    private int pageSize;

    /** 總頁數 */
    private int totalPage;

    /** 總數據條數 */
    private int totalCount;

    public ListPageUtil(List<T> data, int currentPage, int pageSize) {
        if (data == null || data.isEmpty()) {
            throw new IllegalArgumentException("data must be not empty!");
        }

        this.data = data;
        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.totalCount = data.size();
        this.totalPage = (totalCount + pageSize - 1) / pageSize;
        this.lastPage = currentPage-1>1? currentPage-1:1;
        this.nextPage = currentPage>=totalPage? totalPage: currentPage + 1;

    }

    /**
     * 得到分頁後的數據
     * @return 分頁後結果
     */
//    public List<T> getPagedLst() {
//        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();
//        }
//        return data.subList(fromIndex, toIndex);
//    }

    public int getPageSize() {
        return pageSize;
    }

    public List<T> getData() {
        int fromIndex = (currentPage - 1) * pageSize;
        if (fromIndex >= data.size()) {
            return Collections.emptyList();//空數組
        }
        if(fromIndex<0){
            return Collections.emptyList();//空數組
        }
        int toIndex = currentPage * pageSize;
        if (toIndex >= data.size()) {
            toIndex = data.size();
        }
        return data.subList(fromIndex, toIndex);
    }
    public int getLastPage() {
        return lastPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getNextPage() {
        return nextPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }
}

使用方式:

ListPageUtil<ParentBO> pageUtil = new ListPageUtil<>(parentBOList,parent_pageIndex, parent_pageSize);

List<ParentBO> data = pageUtil.getData();
// 其他方法參考工具類方法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章