Java内存分页辅助类

Java内存分页辅助类,第1张

Java内存分页辅助
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class PageData {

    // data
    private List data;

    // page info
    private long pageNum;
    private long pageSize;
    private long totalPage;
    private long totalSize;

    public PageData(List data, long pageSize) {
        if (data == null) {
            throw new RuntimeException("data could not be null");
        }
        if (pageSize <= 0) {
            throw new RuntimeException("page size could not less than 0");
        }
        this.data = data;
        this.pageSize = pageSize;
        this.totalSize = data.size();
        this.pageNum = 0;
        this.totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
    }

    
    public boolean hasNext() {
        return pageNum < totalPage;
    }

    
    public List nextPage() {
        if (hasNext()) {
            return page(++pageNum);
        }
        throw new RuntimeException("out of bounds");
    }

    
    public boolean hasLast() {
        return pageNum > 1;
    }

    
    public List lastPage() {
        if (hasLast()) {
            return page(--pageNum);
        }
        throw new RuntimeException("out of bounds of page data");
    }

    
    public List page(long page) {
        return page(page, this.pageSize);
    }

    
    public List page(long page, long pageSize) {
        if (page <= 0 || pageSize <= 0) {
            throw new RuntimeException("page or page size could not less than 0");
        }
        return data.stream()
                .skip((page - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        // example for this
        List list = new ArrayList<>();
        for (int i = 0; i < 100; i++){
            list.add(i);
        }

        PageData pageData = new PageData<>(list, 30);
        while (pageData.hasNext()){
            List currentPageData = pageData.nextPage();
            System.out.println(currentPageData.size()); // 30, 30, 30, 10
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5481629.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存